【问题标题】:Check whether a password has at least two different special characters检查密码是否至少有两个不同的特殊字符
【发布时间】:2017-06-30 10:21:27
【问题描述】:

我想通过检查用户的密码(一个字符串)是否至少有两个不同的特殊字符来验证它。

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

【问题讨论】:

标签: python python-2.7 passwords


【解决方案1】:

在尝试获取唯一事件时,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多