以下是一个判断字符串中为数字的代码示例:

def is_digit(string):
    try:
        int(string)
        return True
    except ValueError:
        return False

str_list = ['common', 'GE2/0/17(D)', 'GE2/0/19(D)', 'GE2/0/20(D)', 'GE2/0/22(D)']

for string in str_list:
    if is_digit(string):
        print(f'{string} is a number')
    else:
        print(f'{string} is not a number')

输出结果为:

common is not a number
GE2/0/17(D) is not a number
GE2/0/19(D) is not a number
GE2/0/20(D) is not a number
GE2/0/22(D) is not a number

在代码中,is_digit函数使用了tryexcept来尝试将字符串转换为整数。如果转换成功,说明字符串中全为数字,返回True;如果转换失败,说明字符串中包含非数字字符,返回False。然后,遍历字符串列表,调用is_digit函数判断每个字符串是否为数字,并打印相应的结果。

Python 判断字符串是否为数字的代码示例

原文地址: https://www.cveoy.top/t/topic/wmU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录