想要始终以大写字母开头密码?



我正在使用Python 3.6并在Jupyter Notebook上工作。我使用正则表达式进行密码验证的代码工作得非常好。我只想增强我的密码应始终以大写字母开头。我不知道如何在我的 elif 循环中编写正则表达式。代码如下:

import re
import getpass
pattern = re.compile(r"")
while True:
my_str = getpass.getpass("Enter a password: ")
if(8>len(my_str)):
print("Password must be of 8 digits")
if re.search(r"[a-z{1,9}]", my_str) is None:
print("Your Password must contain 1 lowercase letter")
if re.search(r"[!@$&{1,5}]", my_str) is None:
print("Your Password must contain 1 special character")
if re.search(r"[A-Z{1,5}]", my_str) is None:
print("Your Password must contain 1 uppercase letter")
if re.search(r"d{1,5}", my_str) is None:
print("Your Password must contain 1 digit")
elif re.match(r"[A-Za-z0-9@#$%^&+=]{8,}",my_str):
pattern = re.compile(r"[A-Za-z0-9@#$%^&+=]{8,}")
password = pattern.match(my_str)
print(password)
break
else:
print("Not a valid Password")

您可以使用此条件来测试第一个字符是否为大写字母:

my_str[0].isupper()

虽然,你的代码还有更多问题

改进

您在print语句中描述的条件似乎与您正在测试的条件不匹配。

通过示例,条件re.search(r"[a-z{1,9}]", my_str)将检查密码是否包含小写字母或任何字符{1,9}。您可能希望在字符集之外使用括号。

此外,您的代码流不正确,例如,您的while循环的else子句将永远不会被访问。

建议使用valid标志,该标志在不满足条件时变为False,仅当该标志仍True时,循环才会最终退出。否则,将打印未满足的条件并重新开始循环。

固定代码

import re
import getpass
while True:
my_str = getpass.getpass("Enter a password: ")
valid = True
if 8 > len(my_str):
valid = False
print("Password must have at least 8 characters")
if not re.search(r"[a-z]", my_str):
valid = False
print("Your Password must contain 1 lowercase letter")
if not re.search(r"[!@$&]", my_str):
valid = False
print("Your Password must contain 1 special character")
if not re.search(r"[A-Z]", my_str):
valid = False
print("Your Password must contain 1 uppercase letter")
if not re.search(r"d", my_str):
valid = False
print("Your Password must contain 1 digit")
# This is the condition that checks the first character is a capital letter
if my_str and not my_str[0].isupper():
valid = False
print('First character must be a capital letter')
if valid:
break

最新更新