一、isdecimal方法概述
Python的isdecimal()方法是字元串內置方法之一,用於檢測字元串中是否僅包含十進位數字字元。如果字元串只包含數字字元,則返回True;否則返回False。
isdecimal()方法僅判斷10進位數字字元,其它進位字元,如16進位字元或八進位字元等,都會返回False。
二、isdecimal方法語法
str.isdecimal()
該方法沒有參數。
三、isdecimal方法使用示例
示例1:基本使用
str1 = "123456789" str2 = "123456789.0" print(str1.isdecimal()) # True print(str2.isdecimal()) # False
輸出結果:
True
False
示例2:含特殊字元的字元串
str1 = "¥12345" str2 = "-123456789" print(str1.isdecimal()) # False print(str2.isdecimal()) # False
輸出結果:
False
False
示例3:數字和文字混合的字元串
str1 = "12345A" str2 = "123、456" print(str1.isdecimal()) # False print(str2.isdecimal()) # False
輸出結果:
False
False
示例4:應用場景演示
# 判斷是否為手機號碼 def is_phone_number(phone_number): if len(phone_number) != 11: return False if not phone_number.isdecimal(): return False return True # 測試 phone1 = "12345678901" # 不滿足長度要求 phone2 = "12345678ab9" # 含有非數字字元 phone3 = "1a3b5678901" # 含有非數字字元 phone4 = "12345678901" # 符合要求 print(is_phone_number(phone1)) # False print(is_phone_number(phone2)) # False print(is_phone_number(phone3)) # False print(is_phone_number(phone4)) # True
輸出結果:
False
False
False
True
四、isdecimal方法注意事項
isdecimal()方法用於判斷字元串是否為純數字字元,一定要注意字元串中是否含有特殊字元或者其他字元,否則會返回False。通常可以結合其它判斷方法一起使用,實現更加嚴謹的字元串處理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/300768.html