python中isdigit()、isdecimal()和isnumeric的区别!

本文详细介绍了Python中用于判断字符串是否全部由数字组成的三种方法:isdigit(), isdecimal(), 和 isnumeric()。通过实例对比了它们在不同情况下的应用效果,并总结了各自的特点及适用范围。
部署运行你感兴趣的模型镜像

1、函数介绍

isdecimal(...)
 |      S.isdecimal() -> bool
 |      
 |      Return True if there are only decimal characters in S,
 |      False otherwise.  
翻译:如果S中只有十进制字符,则返回True,否则为False。
isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
翻译:如果S中的所有字符都是数字,并且在S中至少有一个字符,则返回True。
isnumeric(...)
 |      S.isnumeric() -> bool
 |      
 |      Return True if there are only numeric characters in S,
 |      False otherwise.
 
翻译:如果S中只有数字字符,则返回True,否则为False。

2、例程

s = '123'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())

结果为:

True
True
True
s = b'123'
print(s.isdigit())
#print(s.isdecimal())
#print(s.isnumeric())

结果为: (只有第一个能正常输出,另外两个报属性错误)

True
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-9e3f7cdf9524> in <module>()
      2 print(s.isdigit())
      3 #print(s.isdecimal())
----> 4 print(s.isnumeric())
 
AttributeError: 'bytes' object has no attribute 'isnumeric'
s = '123.0'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
False
s = '三叁'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
True
s = 'Ⅲ'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
True

3、总结:

isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节)
False: 汉字数字,罗马数字,小数
Error: 无

isdecimal()
True: Unicode数字,全角数字(双字节)
False: 罗马数字,汉字数字,小数
Error: byte数字(单字节)

isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 小数
Error: byte数字(单字节)

转载自:
https://blog.youkuaiyun.com/zhangchen124/article/details/81630631

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值