为什么 isnumeric 无法正常工作?
我在看一个很简单的Python3字符串操作指南时,遇到了一个奇怪的错误:
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Traceback (most recent call last)
<ipython-input-4-859c9cefa0f0> in <module>()
3
4 # test to see if it is numeric
----> 5 string_isnumeric = string.isnumeric()
AttributeError: 'str' object has no attribute 'isnumeric'
问题是,就我所知,str
确实有一个属性,叫做isnumeric
。
5 个回答
0
我碰巧遇到一个奇怪的情况,需要一个脚本同时在Python2和Python3中都能运行。如果其他人也遇到类似的情况,这里是我所做的:
s = "123"
try:
isnum = s.isnumeric()
except AttributeError:
isnum = unicode(s).isnumeric()
5
如果你在用Python 3,可以像下面这样把字符串放在str里:
str('hello').isnumeric()
这样的话,它的表现就和你预期的一样了。
6
一行代码:
unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False
或者
unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
6
isnumeric()
这个函数只能在Unicode字符串上使用。要把一个字符串定义为Unicode,你可以这样修改你的字符串定义:
In [4]:
s = u'This is my string'
isnum = s.isnumeric()
这样做后,它现在会存储False。
注意:我还改了你的变量名,以防你导入了字符串模块。
25
不,str
对象是没有isnumeric
这个方法的。isnumeric
这个方法只适用于unicode对象。换句话说:
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True