2014-04-20 19 views
10

我正在經歷一個非常簡單的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' 

的問題是,據我所知,strDOES有一個屬性,isnumeric

+2

不是在Python 2,更改字符串爲Unicode字符串。 –

+2

請嘗試使用'isdigit'。 – sshashank124

+1

找到答案:默認情況下,文本在Py3中是unicode。 http://stackoverflow.com/questions/16863696/python-isnumeric-function-works-only-on-unicode?rq=1 – Anton

回答

2

isnumeric()只適用於Unicode字符串。要將字符串定義爲Unicode,您可以更改字符串定義,如下所示:

In [4]: 
     s = u'This is my string' 

     isnum = s.isnumeric() 

這將現在存儲False。

注意:如果您導入了模塊字符串,我還更改了變量名稱。

11

不,str對象沒有isnumeric方法。 isnumeric僅適用於unicode對象。換句話說:

>>> d = unicode('some string', 'utf-8') 
>>> d.isnumeric() 
False 
>>> d = unicode('42', 'utf-8') 
>>> d.isnumeric() 
True 
1

一個內襯:

unicode('200', 'utf-8').isnumeric() # True 
unicode('unicorn121', 'utf-8').isnumeric() # False 

或者

unicode('200').isnumeric() # True 
unicode('unicorn121').isnumeric() # False