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