我想验证用户的密码(字符串)是否至少有两个不同的特殊字符。
"!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ "
答案 0 :(得分:0)
尝试获取唯一身份时,set
非常有用。此代码使用set
将密码转换为一组唯一字符。然后,它会使用sum
来计算这些唯一字符in
特殊列表的次数。
<强>代码:强>
def unique_special_count(password):
# provide a list of special characters
special = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ '''
# turn the password into a set of unique characters
# then sum the number of times these unique are in special list
return sum(ch in special for ch in set(password))
测试代码:
test_passwords = (
('notspecial', 0),
('one_special', 1),
('one_special_twice', 1),
('two_specials!', 2),
('three_specials!?', 3),
('three_specials_twice!?!', 3),
)
for pw, count in test_passwords:
print(pw, count, unique_special_count(pw))
assert count == unique_special_count(pw)
<强>结果:强>
notspecial 0 0
one_special 1 1
one_special_twice 1 1
two_specials! 2 2
three_specials!? 3 3
three_specials_twice!?! 3 3