我遇到了一个处理 python isdigit 函数的奇怪问题。
例如:
>>> a = u'\u2466'
>>> a.isdigit()
Out[1]: True
>>> a.isnumeric()
Out[2]: True
为什么这个字符是数字?
有什么方法可以让这个返回 False,谢谢?
编辑,如果我不想将其视为数字,那么如何将其过滤掉?
例如,当我尝试将其转换为 int 时:
>>> int(u'\u2466')
然后UnicodeEncodeError发生了。
U+2466 是带圆圈的数字七(⑦),所以是的,它是一个数字。
如果您对数字的定义与Unicode Consortium的定义不同,您可能必须编写自己的isdigit()方法。
编辑,如果我不想将其视为数字,那么如何将其过滤掉?
如果您只对 ASCII 数字0...感兴趣9,您可以执行以下操作:
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'
字符是CIRCLED DIGIT SEVEN,它是数字和数字。
如果要将数字限制为通常的 0-9,请使用正则表达式:
import re
def myIsDigit(s):
return re.search("[^0-9]", s) is None