python3小技巧之:如何判断字符串是数字

     python中的字符串有专门判断是否为数字的函数isdigit(),当字符中的元素全部是整数,而且至少有一个字符时返回True,否则返回False。

>>> '1235'.isdigit()
True
>>> '1'.isdigit()
True
>>> '1a'.isdigit()
False
>>>

 但是它只能判断包含整数的字符,如果是小数的话,比如‘12.4’就判断不出来;如果是负数的话也不能判断,遍历去判断的话也会很麻烦。

>>> '3.3'.isdigit()
False
>>> '3.0'.isdigit()
False
>>> '3.33.4'.isdigit()
False
>>> '-1'.isdigit()
False

解决方法:用float()将字符串强制做转换,用try捕获异常,没有抛出异常的话说明是数字类型

>>> def fun_isdigit(aString):
...     try:
...        return float(aString)
...     except ValueError as e:
...         print('input is not a number!')
...
>>> fun_isdigit('3.1415')
3.1415
>>> fun_isdigit('3.3')#判断小数
3.3
>>> fun_isdigit('30')#判断整数
30.0
>>> fun_isdigit('-30.9')#判断负数
-30.9
>>> fun_isdigit('ab')#非数字抛异常
input is not a number!

猜你喜欢

转载自blog.csdn.net/kongsuhongbaby/article/details/83072979
今日推荐