Python中isnumeric()函數是判斷一個字符串是否都由數字形式的字符構成,如果是則返回True,否則返回False.
Python的isnumerice()函數判斷的數字形式要比isdecimal()函數和isdigit()函數的范圍要廣,該函數不僅能夠判斷十進制形式的數字,特殊性形式的數字(如阿拉伯數字,Unicode編碼的上角標數字,帶圈的數字),還能夠判斷像漢字中的“一二三”等這種漢字數字。
str.isnumeric()
str就是要被檢查的字符串或字符串變量;
該函數沒有參數;
該函數的返回值是兩個邏輯值:True或False
1、字符串中只有純數字
str1 = "1234"
print(str1.isnumeric())
輸出:True
2、字符串是含有小數點的數字形式
str1 = "12.34"
print(str1.isnumeric())
輸出:False
3、全角數字
str1 = "123456"
print(str1.isnumeric())
輸出:True
4、上角標數字
str1 = "¹²³" #上角標數字
print(str1.isnumeric()) # True
str1 = "¼?" #上角標分數
print(str1.isnumeric()) #True
5、字符串是分數
str1 = "1/4"
print(str1.isnumeric())
輸出:False
6、其它數字形式
str1 = "一二三" #漢字數字
print(str1.isnumeric()) # True
str1 = "ⅠⅡⅢ" #羅馬數字
print(str1.isnumeric()) # True
str1 = "①②③??㈠" #帶圈的數字
print(str1.isnumeric()) #True
str1 = "壹貳叁肆拾佰仟" #大寫漢字數字
print(str1.isnumeric()) # True
str1 = "One" #英文數字單詞
print(str1.isnumeric()) # False
以上在Python 3.8.2中的運行情況如下圖所示:
7、其它進制的數字字符串
str1 = "0b1101"
print(str1.isnumeric())
str1 = "0o37"
print(str1.isnumeric())
str1 = "0X4F"
print(str1.isnumeric())
以上在Python3.8.2中的輸出如下圖所示:
8、字符串包含特殊字符
str1 = "" #空字符串
print(str1.isnumeric()) #False
str1 = "12 34" #含空格
print(str1.isnumeric()) #False
str1 = "abc123" #含字母
print(str1.isnumeric()) #False
str1 = "@123" #含特殊字符
print(str1.isnumeric()) #False
str1 = "武林網VEVB" #不含數字
print(str1.isnumeric()) #False
以上在Python3.8.2中的輸出情況如下圖所示:
本站在前面已經介紹了isdecimal()和isdigit()函數的使用,通過三者的案例對比可以得出以下結論:
(1)isdecimal()函數在中國范圍內僅能判斷[0-9]十個阿拉伯數字,包括半角和全角形式;
(2)isdigit()函數除了isdecimal()函數檢查的數字外,還包括上角標數字[0-9]的全角和半角形式,以及類似①,②等,??等,⑴⑵等一個整體的Unicode數字,⒈ ⒉等整體后帶點的數字格式;
(3)isnumeric()函數除了isdecimal()函數和isdigit()函數能檢查的數字格式外,還包含了像漢字“一二三”等,“? ? ?”等作為整體的分數數字,㈠, ㈡, ㈢,一, 二, 三等作為整體形式的數字,還有用于記賬用的“壹,貳,叁,拾,佰,仟”等形式的數字。
可以使用下面的程序使用上面三個函數把Unicode字符中的所有數字格式輸出:
import unicodedata
list_decimal = [] #isdecimal()為True的數字
list_digit = [] #isdigit()為True的字符
list_numeric = [] #isnumeric()為True的字符
deccnt = digcnt = numcnt = 0
for i in range(2 ** 16):
char = chr(i)
if char.isdecimal():
list_decimal.append(char)
deccnt += 1
if char.isdigit():
list_digit.append(char)
digcnt += 1
if char.isnumeric():
list_numeric.append(char)
numcnt += 1
print('十進制形式,共有:{}個,分別是:{}'.format(deccnt,list_decimal))
print('數字字符共有:{}個,分別是:'.format(digcnt),list_digit)
print('表示數字意義的字符共有:{}個,分別是:{}'.format(numcnt,list_numeric))
雁過留聲,歡迎留下你的見解與認識,共同分享所得。
新聞熱點
疑難解答