str.isdecimal() 和 str.isdigit() 区别示例 [英] str.isdecimal() and str.isdigit() difference example

查看:49
本文介绍了str.isdecimal() 和 str.isdigit() 区别示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 python 文档 我已经来到 .isdecimal() 和 .isdigit() 字符串函数,我没有找到关于它们可用区别的文献.有人可以向我提供这两个函数区别的代码示例吗.

类似行为:

<预><代码>>>>str.isdecimal('1')真的>>>str.isdigit('1')真的>>>str.isdecimal('1.0')错误的>>>str.isdigit('1.0')错误的>>>str.isdecimal('1/2')错误的>>>str.isdigit('1/2')错误的

解决方案

存在 差异,但很少见*.主要是各种unicode字符,比如2:

<预><代码>>>>c = '\u00B2'>>>c.isdecimal()错误的>>>c.isdigit()真的

您还可以使用 isnumeric 方法进一步深入了解 unicode 区分兔子洞:

<预><代码>>>>c = '\u00BD' # ½>>>c.isdecimal()错误的>>>c.isdigit()错误的>>>c.isnumeric()真的

<小时>

*至少,我从未遇到过需要区分包含这些异常情况的不同类型的字符串的生产代码,但肯定在某处存在用例.

Reading python docs I have come to .isdecimal() and .isdigit() string functions and i'm not finding literature too clear on their usable distinction. Could someone supply me with code examples of where these two functions differentiate please.

Similar behaviour:

>>> str.isdecimal('1')
True
>>> str.isdigit('1')
True

>>> str.isdecimal('1.0')
False
>>> str.isdigit('1.0')
False

>>> str.isdecimal('1/2')
False
>>> str.isdigit('1/2')
False

解决方案

There are differences, but they're somewhat rare*. It mainly crops up with various unicode characters, such as 2:

>>> c = '\u00B2'
>>> c.isdecimal()
False
>>> c.isdigit()
True

You can also go further down the careful-unicode-distinction rabbit hole with the isnumeric method:

>>> c = '\u00BD' # ½
>>> c.isdecimal()
False
>>> c.isdigit()
False
>>> c.isnumeric()
True


*At least, I've never encountered production code that needs to distinguish between strings that contain different types of these exceptional situations, but surely use cases exist somewhere.

这篇关于str.isdecimal() 和 str.isdigit() 区别示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆