Python字符串內置判斷數字的三個函數


isdecimal(...)
 |      S.isdecimal() -> bool
 |      
 |      Return True if there are only decimal characters in S,
 |      False otherwise.  
翻譯:如果S中只有十進制字符,則返回True,否則為False。
isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
翻譯:如果S中的所有字符都是數字,並且在S中至少有一個字符,則返回True。
isnumeric(...)
 |      S.isnumeric() -> bool
 |      
 |      Return True if there are only numeric characters in S,
 |      False otherwise.

翻譯:如果S中只有數字字符,則返回True,否則為False。
1 s = '123'
2 print(s.isdigit())
3 print(s.isdecimal())
4 print(s.isnumeric())

結果為:

True
True
True
s = b'123'
print(s.isdigit())
#print(s.isdecimal())
#print(s.isnumeric())

結果為: (只有第一個能正常輸出,另外兩個報屬性錯誤)

True
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last) <ipython-input-19-9e3f7cdf9524> in <module>()  2 print(s.isdigit())  3 #print(s.isdecimal()) ----> 4 print(s.isnumeric()) AttributeError: 'bytes' object has no attribute 'isnumeric'
s = '123.0'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
False
s = '三叄'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
True
s = 'Ⅲ'
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
False
False
True

總結:
isdigit()
True: Unicode數字,byte數字(單字節),全角數字(雙字節)
False: 漢字數字,羅馬數字,小數
Error: 無

isdecimal()
True: Unicode數字,全角數字(雙字節)
False: 羅馬數字,漢字數字,小數
Error: byte數字(單字節)

isnumeric()
True: Unicode數字,全角數字(雙字節),羅馬數字,漢字數字
False: 小數
Error: byte數字(單字節)


轉載:https://www.cnblogs.com/zhouzhishuai/p/8478904.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM