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 篇原创文章 · 获赞 87 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44110998/article/details/103145661