一、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-hant/n/300768.html