Python String isnumeric() 方法是用于字符串处理的 内置 方法。如果字符串中的所有字符都是数字字符,则 issnumeric() 方法返回 “True”,否则返回 “False”。此函数用于检查参数是否包含所有数字字符,如整数、分数、下标、上标、罗马数字等(均以 Unicode 编写)
Syntax:
string.isnumeric()
参数:
isnumeric() does not take any parameters
返回:
- 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())
输出:
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
相关用法
- Numpy string isnumeric()用法及代码示例
- Python String casefold()用法及代码示例
- Python String center()用法及代码示例
- Python String count()用法及代码示例
注:本文由纯净天空筛选整理自AyushSaxena大神的英文原创作品 Python String isnumeric() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。