Python isdigit() function return true for non digit character 2466

2024-05-15 23:46:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在处理python isdigit函数时遇到了一个奇怪的问题。

例如:

>>> a = u'\u2466'
>>> a.isdigit()
Out[1]: True
>>> a.isnumeric()
Out[2]: True

为什么这个字符是数字?

有什么办法让这个返回错误的,谢谢?


编辑,如果我不想把它当作一个数字,那么如何过滤它呢?

例如,当我试图将其转换为int时:

>>> int(u'\u2466')

然后UnicodeEncodeError发生了。


Tags: 函数true编辑错误数字out字符int
3条回答

U+2466是CIRCLED DIGIT SEVEN(⑦),所以是的,它是一个数字。

如果您对什么是数字的定义与Unicode Consortium的定义不同,则可能需要编写自己的isdigit()方法。

Edit, If I don't want to treat it as a digit, then how to filter it out?

如果您只是对ASCII数字09感兴趣,可以执行以下操作:

In [4]: s = u'abc 12434 \u2466 5 def'

In [5]: u''.join(c for c in s if '0' <= c <= '9')
Out[5]: u'124345'

如果您要将某些内容转换为int,则需要^{},而不是isdigit

注意“decimal”不仅仅是0,1,2。。。9,有number of characters可以解释为十进制数字并转换为整数。示例:

#coding=utf8

s = u"1٢٣٤5"
print s.isdecimal() # True
print int(s) # 12345

字符是CIRCLED DIGIT SEVEN,它是数字和数字。

如果要将数字限制为通常的0-9,请使用正则表达式:

import re

def myIsDigit(s):
  return re.search("[^0-9]", s) is None

相关问题 更多 >