gpt4 book ai didi

python - 密码验证器: password needs to contain EXACTLY one spacial character?

转载 作者:行者123 更新时间:2023-12-01 01:32:58 24 4
gpt4 key购买 nike

Task: Password validator
a. The length of the password needs to be from 8 to 30 characters.
b. The password needs to contain at least 2 uppercase characters.
c. The password needs to contain at least 2 lowercase characters.
d. The password needs to contain at least 1 digit.
e. The password needs to contain exactly 1, but not more of the following special characters:
@/%&*_-

这是我的代码:

special_character_set = "@/%&*_-"
is_valid = False
import re
while True:
password = input("please enter a password: ")
if len(password) > 30 or len(password)< 8:
print("The length of the password needs to be from 8 to 30 characters!")
continue
elif re.search('[0-9]', password) is None:
print("The password needs to contain at least 1 digit!")
continue
elif re.search ('[A-Z][A-Z]', password) is None:
print("The password needs to contain at least 2 uppercase characters!")
continue
elif re.search('[a-z][a-z]', password) is None:
print("The password needs to contain at least 2 lowercase characters!")
continue
elif re.search('[@/%&*_-]', password) is None:
print("The password needs to contain one of the following special characters: @/%&*_-!")
continue
else:
is_valid = True
if is_valid:
print("valid password")
break

它有效。然而,条件e)尚未完全满足。如何使密码仅包含一个特殊字符?

最佳答案

len + re.findall() 怎么样? :

...
elif len(re.findall('[@/%&*_-]', password)) != 1:
# Some number of special characters other than 1 was found
...

...
elif len(re.findall('[@/%&*_-]', password)) == 0:
# No special characters were found
...
elif len(re.findall('[@/%&*_-]', password)) > 1:
# Too many special characters were found

(如果您执行后者,请尽量不要运行正则表达式两次)

关于python - 密码验证器: password needs to contain EXACTLY one spacial character?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com