检测字符串是否为数字
s1 = '123456' s2 = '12.45' s3 = 'ab12' s4 = 'abc' s5 = 'ab_12' print(s1.isdigit()) print(s1.isdecimal()) print(s1.isnumeric()) print(s2.isdigit()) print(s2.isdecimal()) print(s2.isnumeric()) print(s3.isalnum()) print(s4.isalpha()) print(s5.isalnum()) True True True False False False True True False
如果将字符串转换为整数,如何做才安全
s1 = '1234a' if s1.isdigit(): print(int(s1)) else: print(s1, '不是数字,无法转换') try: print(int(s1)) except Exception as e: print(e) 1234a 不是数字,无法转换 invalid literal for int() with base 10: '1234a'