python 字符串 isnumeric() 方法用于检查字符串是否由数字字符组成。 如果输入字符串中的所有字符都是数字,并且至少有一个字符,则此方法返回 true。 否则,它将返回 false。
数字字符包括数字字符,以及具有 Unicode 数值属性的所有字符,例如 U+2155、VULGAR FRACTION ONE FIFTH。从形式上讲,数字字符是具有属性值 Numeric_Type=Digit、Numeric_Type=Decimal 或 Numeric_Type=Numeric 的字符。
在下一节中,让我们更详细地研究这种方法。
语法
以下是 python 字符串 isnumeric() 方法的语法 -
str.isnumeric()
参数
python 字符串 isnumeric() 方法不包含任何参数。
返回值
如果字符串中的所有字符都是数字,并且 至少是一个字符,否则为 false。
例以下是 python 字符串 isnumeric() 方法的示例。在这个程序中,我们试图找出字符串 “Welcome2023” 是否是字母数字。
str = "Welcome2023"
result=str.isnumeric()
print("Are all the characters of the string numeric?", result)
在执行上述程序时,将生成以下输出 -
Are all the characters of the string numeric? False
例
让我们看看另一个例子——
str = "2023"
result=str.isnumeric()
print("Are all the characters of the string numeric?", result)
以下是执行上述程序得到的输出 -
Are all the characters of the string numeric? True
例
isnumeric() 方法也将数字的 unicode 表示视为数字。
str = "\u0030" #unicode for 0
result=str.isnumeric()
print("Are all the characters of the string numeric?", result)
通过执行上述程序获得以下输出 -
Are all the characters of the string numeric? True
例
python 字符串 isnumeric() 方法仅将分数的 unicode 表示视为数字。
str = "\u00BE" #unicode for fraction 3/4
result=str.isnumeric()
print("Are all the characters of the string numeric?", result)
上述程序在执行时显示以下输出 -
Are all the characters of the string numeric? True
例