判斷字元是否為數字是Python編程中常見的需求,本文將從多個方面詳細闡述如何使用Python進行字元判斷。
一、isdigit()函數判斷字元是否為數字
Python中可以使用isdigit()函數判斷一個字元是否為數字,該函數返回值為True或False。
str_1 = '123'
str_2 = '23@'
if str_1.isdigit():
print('str_1 is number')
else:
print('str_1 is not number')
if str_2.isdigit():
print('str_2 is number')
else:
print('str_2 is not number')
以上代碼輸出結果為:
str_1 is number
str_2 is not number
二、使用isnumeric()函數判斷字元是否為數字
isnumeric()函數與isdigit()函數類似,都可以用來判斷字元串是否為數字,但是isnumeric()函數會認可任意的數字形式,例如:Unicode數值字元、漢字數字等。
str_1 = '123'
str_2 = '²'
if str_1.isnumeric():
print('str_1 is number')
else:
print('str_1 is not number')
if str_2.isnumeric():
print('str_2 is number')
else:
print('str_2 is not number')
以上代碼輸出結果為:
str_1 is number
str_2 is number
三、正則表達式判斷字元是否為數字
Python中還可以使用正則表達式判斷字元串是否為數字。可以使用re模塊中的match()函數,使用正則表達式判斷輸入字元串是否為數字。
import re
str_1 = '123'
str_2 = 'a23'
pattern = r'^\d+$'
result_1 = re.match(pattern, str_1)
if result_1:
print('str_1 is number')
else:
print('str_1 is not number')
result_2 = re.match(pattern, str_2)
if result_2:
print('str_2 is number')
else:
print('str_2 is not number')
以上代碼輸出結果為:
str_1 is number
str_2 is not number
四、總結
本文從isdigit()函數、isnumeric()函數和正則表達式三個方面詳細闡述了Python如何判斷字元為數字。這些方法可以根據實際需求來選擇使用,在進行具體開發時應根據情況選擇最合適的方法。
原創文章,作者:WTJWU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/375160.html