Python 字串 isdigit() 方法



Python 字串 **isdigit()** 方法用於檢查字串是否僅包含數字。如果輸入字串中的所有字元都是數字,並且至少有一個字元,則此方法返回 True;否則返回 False。

數字包括十進位制字元和需要特殊處理的數字,例如相容的上位數字。這包括不能用於構成 10 進位制數字的數字,例如佉盧文數字。𐩀,𐩂,𐩃,𐩄,𐩅,𐩆,𐩇 是佉盧文數字。正式地說,數字是一個具有 Numeric_Type=Digit 或 Numeric_Type=Decimal 屬性值的字元。

讓我們在下一節中更詳細地瞭解此方法。

語法

以下是 Python 字串 **isdigit()** 方法的語法:

str.isdigit()

引數

Python 字串 **isdigit()** 方法不包含任何引數。

返回值

如果字串中的所有字元都是數字並且至少有一個字元,則 Python 字串 **isdigit()** 方法返回 True;否則返回 False。

示例

以下是 Python 字串 **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()** 方法中,數字還包括佉盧文數字 𐩀,𐩂,𐩃,𐩄,𐩅,𐩆,𐩇。

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
python_strings.htm
廣告