Python isnumeric函数仅适用于unicode

use*_*619 9 python

我试图使用isnumeric函数检查字符串是否为数字但结果不是预期的.该函数仅在其为unicode字符串时才有效.

>>> a=u'1'
>>> a.isnumeric()
True
>>> a='1'
>>> a.isnumeric()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isnumeric'
Run Code Online (Sandbox Code Playgroud)

isnumeric仅在其unicode工作.任何原因?

Art*_*hin 15

只是不同的名字.

'1'.isdigit()是的

  • u'1.5'.isnumeric()= False,使用isdigit或编写自己的函数. (2认同)

maa*_*zza 5

通常,您需要检查Python中的字符串是否为数字.这种情况一直发生,例如用户输入,从数据库中获取数据(可能返回字符串)或读取包含数字的文件.根据您期望的数字类型,您可以使用多种方法.比如解析字符串,使用正则表达式,或者只是尝试将其转换(转换)为数字,看看会发生什么.通常,您还会遇到以Unicode编码的非ASCII数字.这些可能是也可能不是数字.例如2,泰语为2.然而,©只是版权符号,显然不是数字.

链接:http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/