【发布时间】:2020-12-08 08:15:40
【问题描述】:
我正在尝试用 Python 编写一个函数来检查密码并根据以下条件返回 True 或 False:
- 长度必须至少为 8 个字符
- 必须至少包含一个大写字母
- 必须至少包含一个小写字母
- 必须至少包含一个数字
- 它必须至少包含以下特殊字符之一:!@#$%&()-_[]{};':",./? 扭曲的是,它不得包含除所列字符之外的特殊字符,例如空格、~ 或 * 或其他任何内容。
我已经尝试编写代码一周了,并尝试了以下不同的变体:
def password_check(str):
list = ['!', '@', '#', '$', '%', '&', '(', ')', '-', '_', '[', ']', '{', '}', ';', ':', '"', '.', '/', '<', '>', '?']
estr = True
if len(str) >= 8:
for i in str:
if i in list:
estr = True
else:
if i.isnumeric():
estr = True
else:
if i.isupper():
estr = True
else:
if i.islower():
estr = True
else:
return False
else:
estr = False
return estr
但是代码不能按预期工作,因为例如,如果只有小写字母,它会返回 True。所以我尝试了以下方法:
def password_check(str):
list = ['!', '@', '#', '$', '%', '&', '(', ')', '-', '_', '[', ']', '{', '}', ';', ':', '"', '.', '/', '<', '>', '?']
if any(i.isupper() for i in str) and any(i.islower() for i in str) and any(i.isdigit() for i in str) and len(str) >= 8 and any(i in list for i in str):
estr = True
else:
return False
但当使用无效字符(例如 ~)时,它不会返回 False。下面的函数调用应该返回 True、True、False、False、False、True、False 和 False。
print(password_check("tHIs1sag00d.p4ssw0rd."))
print(password_check("3@t7ENZ((T"))
print(password_check("2.shOrt"))
print(password_check("all.l0wer.case"))
print(password_check("inv4l1d CH4R4CTERS~"))
print(password_check('X)ndC@[?/fVkoN/[AkmA0'))
print(password_check(':>&BhEjGNcaSWotpAy@$tJ@j{*W8'))
print(password_check('ZW}VoVH.~VGz,D?()l0'))
如果有人指出我正确的方向,我将不胜感激。
【问题讨论】:
-
Link这个回答你的问题?
-
尝试将您的代码重组为
if ... elif ... elif ...链并否定所有条件,以便您有机会在返回 False 之前打印一条条件失败的消息。然后你也可以使用调试器