2013-05-31 24 views
8

我試圖檢查一個字符串是否使用isnumeric函數是數字,但結果不是預期的。該函數只有在其unicode字符串時才起作用。Python的數字函數只適用於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' 

isnumeric只有在其unicode纔有效。任何原因?

回答

5

通常您會想要檢查Python中的字符串是否是數字。這個 總是會發生,例如用戶輸入,從數據庫中獲取數據(可能返回一個字符串)或讀取包含 數字的文件。根據您期望的號碼類型,您可以使用多種方法。比如解析字符串,使用正則表達式或 只是試圖將其轉換(轉換)爲一個數字,並看看發生了什麼 。 通常您還會遇到非ASCII碼,編碼爲 Unicode。這些可能是也可能不是數字。例如2,這是泰文中的 中的2。然而©僅僅是版權符號,顯然不是 的編號。

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

12

只是不同的名字。

「1'.isdigit() 真

+0

字符串'a'也可以包含浮點值,所以我不能使用isdigit .. – user1050619

+2

u'1.5'.isnumeric()= False,使用isdigit或編寫自己的函數。 –

4

按照Python documentationisnumeric只存在於Unicode對象:

以下方法僅存Unicode對象:

unicode.isnumeric()

如果S中只有數字字符,則返回True,否則返回False。數字字符包括數字字符和具有Unicode數字值屬性的所有字符,例如U + 2155,VULGAR FRACTION ONE FIFTH。

1

isnumeric()已擴展爲Unicode字符串不同numeral systems支持。在美洲和歐洲使用Hindu-Arabic numeral system,其由數字組成。

印度 - 阿拉伯數字也被Unicode統稱爲歐洲數字。

的其他數字系統,可作爲:

  • 羅馬數字
  • 古希臘數字
  • 泰米爾數字
  • Japaneese數字
  • ,葡萄牙語數字
  • 韓國數字

有關數字系統的更多信息可以在這裏找到:wikiwand.com/en/Numerals_in_Unicode#/Numerals_by_script

的Unicode subscriptsuperscriptfractions也被認爲是由isnumeric()功能有效數字。


您可以使用下面的isnumeric()函數來檢查字符串是否爲非unicode數字。

l = ['abc' + chr(255), 'abc', '123', '45a6', '78b', u"\u2155", '123.4', u'\u2161', u'\u2168'] 

def isnumeric(s): 
    '''Returns True for all non-unicode numbers''' 
    try: 
     s = s.decode('utf-8') 
    except: 
     return False 

    try: 
     float(s) 
     return True 
    except: 
     return False 


for i in l: 
    print i, 'isnumeric:', isnumeric(i) 

print '--------------------' 
print u'\u2169', 'isnumeric', u'\u2169'.isnumeric() 
print u'\u2165', 'isnumeric', u'\u2165'.isnumeric() 

編輯:因爲我有足夠的聲譽超過2個鏈接添加到這個答案,我會盡快更新這個帖子。

相關問題