如何在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

更新於:2022年12月7日

740 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.