Python String isdigit() 方法是用於字符串處理的 內置 方法。如果字符串中的所有字符都是數字,則 isdigit() 方法返回 “True”,否則返回 “False”。該函數用於檢查參數是否包含數字如 0123456789
用法:
string.isdigit()
參數:
isdigit() 不帶任何參數
返回值:
- True - 如果字符串中的所有字符都是數字。
- False - 如果字符串包含 1 個或多個非數字。
Errors And Exceptions:
- 它不接受任何參數,因此如果傳遞參數則返回錯誤
- 上標和下標與十進製字符一起被視為數字字符,因此,isdigit() 返回 “True”。
- 羅馬數字、貨幣分子和分數不被視為數字。因此,isdigit() 返回 “False”
範例1:
Input:string = '15460' Output:True Input:string = '154ayush60' Output:False
Python3
# Python code for implementation of isdigit()
# checking for digit
string = '15460'
print(string.isdigit())
string = '154ayush60'
print(string.isdigit())
輸出:
True False
範例2:
應用:使用字符的ASCII值,使用isdigit()函數計算並打印所有數字。
算法:
- 初始化一個新字符串和一個變量 count=0。
- 使用ASCII值遍曆每個字符,檢查字符是否為數字。
- 如果是數字,則將計數加 1 並將其添加到新字符串中,否則遍曆到下一個字符。
- 打印計數器的值和新字符串。
Python3
# Python program to illustrate
# application of isdigit()
# initialising Empty string
newstring =''
# Initialising the counters to 0
count = 0
# Incrementing the counter if a digit is found
# and adding the digit to a new string
# Finally printing the count and the new string
for a in range(53):
b = chr(a)
if b.isdigit() == True:
count+= 1
newstring+= b
print("Total digits in range:", count)
print("Digits:", newstring)
輸出:
Total digits in range:5 Digits:01234
在 Python 中,上標和下標(通常使用 Unicode 編寫)也被視為數字字符。因此,如果字符串包含這些字符和十進製字符,則 isdigit() 返回 True。羅馬數字、貨幣分子和分數(通常使用 Unicode 編寫)被認為是數字字符而不是數字。如果字符串包含這些字符,則 isdigit() 返回 False。要檢查字符是否為數字字符,可以使用 isnumeric() 方法。
範例3:
包含數字和數字字符的字符串
Python3
s = '23455'
print(s.isdigit())
# s = '²3455'
# subscript is a digit
s = '\u00B23455'
print(s.isdigit())
# s = '½'
# fraction is not a digit
s = '\u00BD'
print(s.isdigit())
輸出:
True True False
相關用法
- Numpy string isdigit()用法及代碼示例
- Python Pandas Series.str.isdigit()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String center()用法及代碼示例
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 Python String isdigit() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。