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
廣告