我有一个我不想使用正则表达式的场景。我有一串密码。我想检查条件,它应该包含字母,数字,大写字母,小写字母,特殊字符。没有正则表达式如何实现呢?最快的方法是什么?我列出了a-z和A-Z以及0-9和特殊字符的列表。但这会浪费时间将所有内容写入列表。谢谢!
您可以使用any
检查密码中的任何字符是否在您描述的字符集中。然后将其包装在all
中,以确保满足您的每个要求之一。
import string
def validate_password(password):
char_sets = {string.ascii_lowercase,
string.ascii_uppercase,
string.digits,
string.punctuation}
return all(any(letter in char_set for letter in password) for char_set in char_sets)
例如
>>> validate_password('password')
False
>>> validate_password('Password1!')
True
您可以使用以下一组测试:
pw = 'Ab1!'
has_alpha = any([x.isalpha() for x in pw])
has_num = any([x.isdigit() for x in pw])
has_upper = any([x.isupper() for x in pw])
has_lower = any([x.islower() for x in pw])
has_symbol = any([not x.isalnum() for x in pw])
is_proper_pw = has_alpha and has_num and has_upper and has_lower and has_symbol