Python 字符串 isnumeric() 方法



Python 字符串 isnumeric() 方法用于检查字符串是否仅包含数字字符。如果输入字符串中的所有字符都是数字字符,并且至少有一个字符,则此方法返回 True。否则,它返回 False。

数字字符包括数字字符,以及所有具有 Unicode 数字值属性的字符,例如 U+2155,俗称五分之一。正式地,数字字符是指其属性值为 Numeric_Type=Digit、Numeric_Type=Decimal 或 Numeric_Type=Numeric 的字符。

在以下部分,让我们更详细地了解此方法。

语法

以下是 Python 字符串 isnumeric() 方法的语法:

str.isnumeric()

参数

Python 字符串 isnumeric() 方法不包含任何参数。

返回值

Python 字符串 isnumeric() 方法如果字符串中的所有字符都是数字字符,并且至少有一个字符,则返回 True,否则返回 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

示例

数字的 Unicode 表示形式也被 isnumeric() 方法视为数字。

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

示例

佉卢文数字,如 𐩀、𐩂、𐩃、𐩄、𐩅、𐩆、𐩇 被视为数字。因此,Python 字符串 isnumeric() 方法返回 True。

str = "𐩁𐩂𐩃" 
result=str.isnumeric()
print("Are all the characters of the string numeric?", result)

上述程序的输出显示如下:

Are all the characters of the string numeric? True
python_strings.htm
广告

© . All rights reserved.