python String isdigit() 方法用于检查字符串是否由数字组成。 如果输入字符串中的所有字符都是数字并且至少有一个字符,则此方法返回 true。 否则,它将返回 false。
数字包括十进制字符和需要特殊处理的数字,例如 兼容性上标数字。这包括不能用于形成以 10 为基数的数字的数字,例如 Kharosthi 数字。从形式上讲,数字是具有 property value 的字符 Numeric_Type = 数字或 Numeric_Type = 十进制。
让我们在下一节中更详细地研究这种方法。
语法
以下是 python String isdigit() 方法的语法 -
str.isdigit()
参数
python 字符串 isdigit() 方法不包含任何参数。
返回值
如果字符串中的所有字符都是数字,并且 至少是一个字符,否则为 false。
例以下是 python String isdigit() 方法的示例。在此程序中,将创建一个字符串 “1235” 并调用 isdigit() 方法。
str = "1235"
result=str.isdigit()
print("Are all the characters of the string digits?", result)
在执行上述程序时,将生成以下输出 -
Are all the characters of the string digits? True
例
在 python 字符串 isdigit() 方法中,数字还包括 kharosthi 数字。它们是
str = " "
result=str.isdigit()
print("Are all the characters of the string digits?", result)
以下是执行上述程序得到的输出 -
Are all the characters of the string digits? True
例
unicode 表示形式的数字上标也被此 isdigit() 方法视为数字。
str = "\u00B3" #superscript of 3
result=str.isdigit()
print("Are all the characters of the string digits?", result)
通过执行上述程序获得以下输出 -
Are all the characters of the string digits? True
例
isdigit() 方法仅将数字的 Unicode 表示形式视为数字。
str = "\u0030" #unicode for 0
result=str.isdigit()
print("Are all the characters of the string digits?", result)
上述程序在执行时显示以下输出 -
Are all the characters of the string digits? True
例
分数不被视为数字。因此,如果创建的字符串包含 Unicode 格式或任何其他格式的分数, 该方法返回 false。
str = "\u00BE" #unicode for fraction 3/4
result=str.isdigit()
print("Are all the characters of the string digits?", result)
上述程序的输出显示如下 -
Are all the characters of the string digits? False