检查密码是否至少包含两个不同的特殊字符

时间:2017-02-12 11:26:31

标签: python python-2.7 passwords

我想验证用户的密码(字符串)是否至少有两个不同的特殊字符

  • 特殊字符"!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ "

1 个答案:

答案 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