Python String isnumeric() 方法
Python String isnumeric()方法是用于字符串处理的内置方法。如果字符串中的所有字符都是数字字符,则 issnumeric() 方法返回“True”,否则返回“False”。该函数用于检查参数是否包含所有数字字符,如整数、分数、下标、上标、罗马数字等(全部用Unicode编写)
Syntax:
string.isnumeric()
Parameters:
isnumeric() does not take any parameters
Returns :
- True – If all characters in the string are numeric characters.
- False – If the string contains 1 or more non-numeric characters.
Errors and Exceptions:
- It does not contain any arguments, therefore, it returns an error if a parameter is passed.
- Whitespaces are not considered to be numeric, therefore, it returns “False”
- Subscript, Superscript, Fractions, Roman numerals (all written in Unicode)are all considered to be numeric, Therefore, it returns “True”
示例 1:
Input : string = '1889345'
Output : True
Input : string = '\u00BD'
Output : True
Input : string = '123ayu456'
Output : False
Python3
# Python code for implementation of isnumeric()
# checking for numeric characters
string = '123ayu456'
print(string.isnumeric())
string = '123456'
print( string.isnumeric())
Python3
# Python implementation to count numeric characters
# in a string and print non numeric characters
# Given string
# Initialising the counter to 0
string ='123geeks456for789geeks'
count = 0
newstring1 =""
newstring2 =""
# Iterating the string and checking for numeric characters
# Incrementing the counter if a numeric character is found
# And adding the character to new string if not numeric
# Finally printing the count and the newstring
for a in string:
if (a.isnumeric()) == True:
count+= 1
else:
newstring1+= a
print(count)
print(newstring1)
string ='123ayu456'
count = 0
for a in string:
if (a.isnumeric()) == True:
count+= 1
else:
newstring2+= a
print(count)
print(newstring2)
输出:
False
True
示例 2:
应用:在Python中给定一个字符串,计算字符串中数字字符的个数,并将它们从字符串中删除,然后打印字符串。
Input : string = '123geeks456for789geeks'
Output : 9
geeksforgeeks
Input : string = '123ayu456'
Output : 6
ayu
算法:
- 将一个空的 NewString 和变量 count 初始化为 0。
- 逐个字符遍历给定的字符串,直到字符长度,检查字符是否为数字字符。
- 如果是数字字符,则将计数器加 1 并且不将其添加到新字符串中,否则遍历到下一个字符并继续将字符添加到新字符串中(如果不是数字)。
- 打印计数器的值和 NewString。
Python3
# Python implementation to count numeric characters
# in a string and print non numeric characters
# Given string
# Initialising the counter to 0
string ='123geeks456for789geeks'
count = 0
newstring1 =""
newstring2 =""
# Iterating the string and checking for numeric characters
# Incrementing the counter if a numeric character is found
# And adding the character to new string if not numeric
# Finally printing the count and the newstring
for a in string:
if (a.isnumeric()) == True:
count+= 1
else:
newstring1+= a
print(count)
print(newstring1)
string ='123ayu456'
count = 0
for a in string:
if (a.isnumeric()) == True:
count+= 1
else:
newstring2+= a
print(count)
print(newstring2)
输出:
9
geeksforgeeks
6
ayu