Python - 判斷字符串是否爲數字、字母、空格等

函數 說明 實例
isdigit 數字 '123'.isdigit()
isalpha 字母 'Abc'.isalpha()
isspace 空格 ' '.isspace()
isdecimal 十進制數字 '123'.isdecimal()
islower 小寫字母 'abc'.islower()
isupper 大寫字母 'ABC'.isupper()
istitle 單詞首字母大寫 'Abc'.istitle()
isalnum 字母或數字 'Ab3'.isalnum()

舉一個密碼驗證的小例子

def checkio(s):
    fs = ''.join(filter(str.isalnum, s)) # 只保留字母和數字
    return (
            len(fs) >= 1        # 至少有一個字母或數字
        and len(s)  >= 5       # 至少有5個字符
        and not fs.isalpha()    # 至少有一個數字
        and not fs.isdigit()    # 至少有一個字母
        and not fs.islower()    # 不是所有的字母都是小寫的
        and not fs.isupper()    # 不是所有的字母都是大寫的
    )
print(checkio('Ab123'))
發佈了63 篇原創文章 · 獲贊 124 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章