Python String isdigit() 方法
Python String isdigit()方法是用于字符串处理的内置方法。如果字符串中的所有字符都是数字,isdigit() 方法返回“ True ”,否则返回“False”。该函数用于检查参数是否包含数字,例如0123456789
Syntax:
string.isdigit()
Parameters:
isdigit() does not take any parameters
Returns:
- True – If all characters in the string are digits.
- False – If the string contains 1 or more non-digits.
Errors And Exceptions:
- It does not take any arguments, therefore it returns an error if a parameter is passed
- Superscript and subscripts are considered digit characters along with decimal characters, therefore, isdigit() returns “True”.
- The Roman numerals, currency numerators, and fractions are not considered to be digits. Therefore, the isdigit() returns “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())
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)
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
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