1
我想通过检查来验证用户的密码(字符串),是否有至少两个不同的特殊字符。检查是否密码至少有两个不同的特殊字符
- 特殊字符
"!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~ "
我想通过检查来验证用户的密码(字符串),是否有至少两个不同的特殊字符。检查是否密码至少有两个不同的特殊字符
"!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~ "
当试图获得独一无二的事件,set
是非常有用的。此代码使用set
将密码转换为一组唯一字符。然后,它使用sum
计算这些独特的字符是in
特殊列表的次数。
代码:
def unique_special_count(password):
# provide a list of special characters
special = '''!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~ '''
# 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
[Python中的可能的复制:计数occurr数在一个字符串列表项(http://stackoverflow.com/questions/24524531/python-count-number-of-occurrences-of-list-items-in-a-string) – Aurora0001
@ Aurora0001分配办法我要检查不同的特殊字符的存在,所以我应该如何保持这个数字? –
啊,你需要确保两个**不同的**存在?你也许可以使用[这个答案](http://stackoverflow.com/a/24524593/6650102)第二种方法,检查两个值都大于零。 – Aurora0001