检查变量python中的大小写、符号和数字

2024-10-02 22:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用正则表达式来分别检查他们,所以我更喜欢使用re的答案。在

一个我用来分别找到它们的例子:

 if re.search(r'[A-Z]', userpass):
    score += 5

但是,我想检查变量是否包含所有参数(大写/小写、符号和数字),因此使用搜索每次都会返回true,因为它只检查是否有一个数字,但我想检查是否有一个数字,大小写和符号。我想检查的符号是:!$%^&;*()-\

另外,对clarfy来说,我对python相当陌生,所以除了基本的东西之外,几乎所有的东西对我来说都是新的,所以我使用regex,因为我发现它非常简单


Tags: 答案retruesearch参数if符号数字
3条回答

对于非regex解决方案,您可以使用以下内容:

def check_userpass(userpass):
    has_lower = userpass.upper() != userpass
    has_upper = userpass.lower() != userpass
    has_number = any(ch.isdigit() for ch in userpass)
    has_symbol = any(ch in "!$%^&*()-_=+" for ch in userpass)
    return has_lower and has_upper and has_number and has_symbol

不带正则表达式:

cond1 = any(c.isalpha() for c in password)
cond2 = any(c.isnumber() for c in password)
cond3 = any(word in password for word in '!$%^&*()-_=+')
valid = cond1 and cond2 and cond3

我认为它可能更适合使用正则表达式。相反,我只使用all()any()

checks = [[chr(c) for c in range(97, 123)] + [chr(c) for c in range(65, 91)], list("!$%^&*()-_=+"), [str(i) for i in range(10)]]

if all(any(c in check for c in userpass) for check in checks):
    score += 5

相关问题 更多 >