在Python中,isdigit()是用于字符串处理的内置方法。如果字符串中的所有字符均为数字,则isdigit()方法返回“True”,否则,返回“False”。此函数用于检查参数是否包含数字,例如:0123456789
用法:
string.isdigit()
参数:
isdigit() does not take any parameters
返回:
1.True- If all characters in the string are digits.
2.False- If the string contains 1 or more non-digits.
例子:
Input:string = '15460'
Output:True
Input:string = '154ayush60'
Output:False
# Python code for implementation of isdigit()
# checking for digit
string = '15460'
print(string.isdigit())
string = '154ayush60'
print(string.isdigit())
输出:
True
False
错误与异常
它不接受任何参数,因此如果传递参数则返回错误
上标和下标被视为数字字符以及十进制字符,因此,isdigit()返回“True”。
罗马数字,货币分子和小数不被视为数字。因此,isdigit()返回“False”
应用:使用字符的ascii值,使用isdigit()功能对所有数字进行计数和打印。
算法
1.初始化一个新字符串,变量count = 0。
1.使用ascii值遍历每个字符,检查该字符是否为数字。
2.如果是数字,则将计数加1并将其添加到新字符串中,否则遍历下一个字符。
3.打印计数器的值和新字符串。
# 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