例如:
检查文本中的所有字符是否都是数字:
txt = "565543"x = txt.isnumeric()print(x)
1、定义和用法
如果所有字符都是数字(0-9),则isnumeric()
方法返回True,否则返回False。
指数(例如²
和¾
)也被视为数字值。
"-1"
和"1.5"
不视为数字值,因为字符串中的所有字符必须为数字,并且-和.不是。
2、调用语法
string.isnumeric()
3、参数说明
没有参数。
4、 isdigit() 、isnumeric()、isdecimal() 的区别
1)区别
数字类型 | 函数 | 能否判别 |
---|---|---|
unicode(半角) | isdigit() isnumeric() isdecimal() | True True True |
全角数字 | isdigit() isnumeric() isdecimal() | True True True |
bytes数字 | isdigit() isnumeric() isdecimal() | True False False |
阿拉伯数字 | isdigit() isnumeric() isdecimal() | False True False |
汉字数字 | isdigit() isnumeric() isdecimal() | False True False |
2)示例代码
num = "1"#unicodeprint(num.isdigit()) # Trueprint(num.isdecimal()) # Trueprint(num.isnumeric()) # Truenum = "1"# 全角print(num.isdigit()) # Trueprint(num.isdecimal()) # Trueprint(num.isnumeric()) # Truenum = b"1"# byteprint(num.isdigit()) # Trueprint(num.isdecimal()) # AttributeError ‘bytes’ object has no attribute ‘isdecimal’print(num.isnumeric()) # AttributeError ‘bytes’ object has no attribute ‘isnumeric’num = "IV"# 罗马数字print(num.isdigit()) # Trueprint(num.isdecimal()) # Falseprint(num.isnumeric()) # Truenum = "四"# 汉字print(num.isdigit()) # Falseprint(num.isdecimal()) # Falseprint(num.isnumeric()) # True
5、使用示例
例如:
检查字符是否为数字:
a = "\u0030" #unicode for 0b = "\u00B2" #unicode for ²c = "10km2"d = "-1"e = "1.5"print(a.isnumeric())print(b.isnumeric())print(c.isnumeric())print(d.isnumeric())print(e.isnumeric())