python isnumeric函数用法_Python string isnumeric()用法及代码示例

在Python中,isnumeric()是用于字符串处理的内置方法。如果字符串中的所有字符均为数字字符,则issnumeric()方法返回“True”,否则,返回“False”。此函数用于检查参数是否包含所有数字字符,例如:整数,分数,下标,上标,罗马数字等(均以unicode编写)

用法:

string.isnumeric()

参数:

isnumeric() does not take any parameters

返回:

1.True- If all characters in the string are numeric characters.

2.False- If the string contains 1 or more non-numeric characters.

例子:

Input:string = '1889345'

Output:True

Input:string = '\u00BD'

Output:True

Input:string = '123ayu456'

Output:False

# Python code for implementation of isnumeric()

# checking for numeric characters

string = '123ayu456'

print(string.isnumeric())

string = '123456'

print( string.isnumeric())

输出:

False

True

错误和异常

它不包含任何参数,因此,如果传递了参数,它将返回错误。

空格不被视为数字,因此它返回“False”

下标,上标,分数,罗马数字(均以unicode编写)均被视为数字,因此,它返回“True”

应用:给定python中的字符串,请计算字符串中数字字符的数量,然后将其从字符串中删除并打印该字符串。

例子:

Input:string = '123geeks456for789geeks'

Output:9

geeksforgeeks

Input:string = '123ayu456'

Output:6

aye

算法

1.初始化一个空的新字符串并将变量计数设置为0。

1.逐字符遍历给定的字符串字符直至其长度,检查字符是否为数字字符。

2.如果它是数字字符,则将计数器加1,不要将其添加到新字符串中,否则遍历下一个字符,如果不是数字,则继续将字符添加到新字符串中。

3.打印计数器和新字符串的值。

# 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值