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'))
posted @ 2019-11-19 21:05  程序猿杂记  阅读(161)  评论(0)    收藏  举报