Python判断字符串是否是数值型数据方法

判断字符串是否是数值型字符串

将字符串用float函数转换,如果抛出ValueError异常,则不是有效的数值型字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def is_numeric(s):
try:
float(s)
except ValueError:
return False
else:
return True
print(is_numeric('+100')) # True
print(is_numeric('5e2')) # True
print(is_numeric('-1E-16')) # True
print(is_numeric('3.1416')) # True
print(is_numeric('-123')) # True
print(is_numeric('12e')) # False
print(is_numeric('1a3.14')) # False
print(is_numeric('1.2.3')) # False
print(is_numeric('+-5')) # False
print(is_numeric('12e+4.3')) # False

判断字符串是否只包含数字

用字符串的str.isdigit()方法,判断字符串是否只包含数字。

1
2
3
4
5
6
7
>>> '0731'.isdigit()
True
>>> '07a31'.isdigit()
False
>>> '+0731'.isdigit()
False
>>>

判断字符串是否是整数型字符串

将字符串用float函数转换,然后再用is_integer()判断浮点数值是否是整数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def is_int(s):
try:
f = float(s)
except ValueError:
return False
else:
if f.is_integer():
return True
else:
return False
print(is_int('+123')) # True
print(is_int(10.0)) # True
print(is_int(10.2)) # False

只是判断数值是整数还是浮点数

isinstance()判断数值是整数还是浮点数。

1
2
3
4
5
6
7
>>> isinstance(+123, int)
True
>>> isinstance(-123.45, int)
False
>>> isinstance(-123.45, float)
True
>>>

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄