python中的str.isdigit、isnumeric和isdecimal有什么区别? [英] What's the difference between str.isdigit, isnumeric and isdecimal in python?

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

问题描述

当我运行这些方法时

s.isdigit()s.isnumeric()s.isdecimal()

对于 s 的每个值(当然是字符串),我总是得到输出或全部为 True 或全部为 False .三者有什么区别?你能提供一个例子,给出两个真一个假(或反之亦然)?

解决方案

主要是关于 unicode 分类.以下是一些显示差异的示例:

<预><代码>>>>定义垃圾邮件:... 对于 'isnumeric'、'isdecimal'、'isdigit' 中的属性:... print(attr, getattr(s, attr)())...>>>垃圾邮件('½')isnumeric 真十进制错误isdigit 错误>>>垃圾邮件('³')isnumeric 真十进制错误isdigit 真

具体行为在官方文档中这里.

找到所有这些的脚本:

导入系统导入 unicodedata从集合导入 defaultdictd = defaultdict(列表)对于 i 在范围内(sys.maxunicode + 1):s = chr(i)t = s.isnumeric(), s.isdecimal(), s.isdigit()如果 len(set(t)) == 2:尝试:名称 = unicodedata.name(s)除了值错误:name = f'codepoint{i}'打印(S,名称)d[t].append(s)

When I run these methods

s.isdigit()
s.isnumeric()
s.isdecimal()

I always got as output or all True, or all False for each value of s (which is of course a string). What's​ the difference between the three? Can you provide an example that gives two trues and one false (or viceversa)?

解决方案

It's mostly about unicode classifications. Here's some examples to show discrepancies:

>>> def spam(s):
...     for attr in 'isnumeric', 'isdecimal', 'isdigit':
...         print(attr, getattr(s, attr)())
...         
>>> spam('½')
isnumeric True
isdecimal False
isdigit False
>>> spam('³')
isnumeric True
isdecimal False
isdigit True

Specific behaviour is in the official docs here.

Script to find all of them:

import sys
import unicodedata
from collections import defaultdict

d = defaultdict(list)
for i in range(sys.maxunicode + 1):
    s = chr(i)
    t = s.isnumeric(), s.isdecimal(), s.isdigit()
    if len(set(t)) == 2:
        try:
            name = unicodedata.name(s)
        except ValueError:
            name = f'codepoint{i}'
        print(s, name)
        d[t].append(s)

这篇关于python中的str.isdigit、isnumeric和isdecimal有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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