如何在Python中檢查Unicode字串是否只包含數字字元?
在這篇文章中,我們將瞭解如何在Python中檢查Unicode字串是否只包含數字字元。
我們將使用內建函式isnumeric()來檢查字串中是否只有數字字元。它類似於isdigit()和isdecimal(),但它具有更廣泛的接受範圍。
它對數字、上標、下標、分數、羅馬數字等返回True。我們也可以使用isdigit()和isdecimal(),但isnumeric()比其他兩個更有效。
示例1
在下面的示例中,我們採用一個Unicode字串作為輸入,並使用isnumeric()函式檢查給定的Unicode字串是否只有數字字元。
str1 = u"124345" print("The given string is") print(str1) print("Checking if the given Unicode string contains only numeric characters") res = str1.isnumeric() print(res)
輸出
上面示例的輸出如下:
The given string is 124345 Checking if the given unicode string contains only numeric characters True
示例2
在下面的示例中,我們使用與上面相同的程式,但我們採用另一個字串作為輸入,並檢查該Unicode字串是否只包含數字字元。
str1 = u"1243!@45" print("The given string is") print(str1) print("Checking if the given Unicode string contains only numeric characters") res = str1.isnumeric() print(res)
輸出
上面示例的輸出如下:
The given string is 1243!@45 Checking if the given unicode string contains only numeric characters False
廣告