Python中如何使用函数来检查字符串是否为数字?
发布时间:2023-06-19 12:08:03
在Python中,我们可以使用内置函数来检查字符串是否为数字。这些函数包括:
1. isdigit()
isdigit()函数是一种可以检查字符串是否由数字组成的方法。如果字符串只包含数字,则返回True;否则,返回False。例如:
>>> '12345'.isdigit() True >>> '12345abc'.isdigit() False
2. isnumeric()
isnumeric()函数是另一种检查字符串是否由数字组成的方法。它与isdigit()函数类似,但可以用于不仅仅是阿拉伯数字的字符串。例如:
>>> '?'.isnumeric() True >>> '?????'.isnumeric() True >>> '12345abc'.isnumeric() False
3. isdecimal()
isdecimal()函数是一种只能用于表示十进制数字字符的方法。如果字符串中只包含十进制数字,则返回True;否则,返回False。例如:
>>> '0123456789'.isdecimal() True >>> '?????'.isdecimal() False
4. 使用正则表达式
如果以上函数不能满足需求,可以使用正则表达式来匹配数字。以下是一个简单的正则表达式,它将匹配包含整数、小数、正数、负数的任何数字字符串:
import re
def is_number(s):
pattern = re.compile("^[-+]?[0-9]+(\.[0-9]*)?$")
return pattern.match(s) is not None
print(is_number('123')) # True
print(is_number('-123.4')) # True
print(is_number('123.abc')) # False
