我必须建立一个输入密码的程序。密码必须至少包含8个字符,以字母开头,大写和小写字母,没有空格和至少2位数字。
除了最后2个,我还有其他一切。
我尝试使用for循环来查看是否有空格或数字,但它只有在整个密码由空格或数字组成时才有效。如果有一个数字或一个空格,如果在错误信息中打印出密码中有多少个字符,而不仅仅是有多少个数字或空格。我知道这是因为for循环而发生的,但我仍然坚持如何修复它。
这是我到目前为止:
again = 'y'
while again == 'y':
minimum_characters = 8
error = 0
print('Password must contain 8 characters, start with a letter,')
print(' have no blanks, at least one uppercase and lowercase letter,')
print(' and must contain at least 2 digits.')
password = input('Enter a password: ')
passlength = len(password)
#validity checks for errors
if passlength < minimum_characters:
error += 1
print (error, '- Not a valid password. Must contain AT LEAST 8 characters. PW entered has', passlength, '.')
if not password[0].isalpha():
error += 1
print(error, '- The password must begin with a letter.')
if password.isalpha():
error += 1
print(error, '- The password must contain at least 2 digits.')
if password.isupper():
error += 1
print(error, '- You need at least one lower case letter.')
if password.islower():
error += 1
print(error,'- You need at least one upper case letter.')
again = input('Test another password? (Y or N): ')
again = again.lower()
if " " in password:
error += 1
print(error, '- Not a valid password. It contains spaces.')
if len([x for x in pwd if x.isdigit()]) < 2:
error += 1
print(error, '- The password must contain at least 2 digits.')
要在字符串包含少于2位数时报告错误,您可以使用:
if sum(map(str.isdigit, password)) < 2:
此外,您对大写和小写字母的检查不正确:
if password.isupper():
检查所有字符是否都是大写的。要检查是否有任何字符是大写的,您可以使用:
any(map(str.isupper, password))
“(......)没有空格,至少有2位数字。”
一些选项可用于计算任何字符/数字的出现次数。只需替换您需要的内容(示例中的数字和空格):
if any([x for x in password if x == " "]):
# 1 or more spaces in password
if password.count(" ") > 0:
# 1 or more spaces in password
if len([x for x in password if x.isdigit()]) < 2:
# less than 2 digits
用户正则表达式
import re
sequence = "1Sentence1e"
if re.match("(?:\d.*?){2,}", sequence):
print("Match!")
else:
print("Not match!")
正则表达式匹配javascript语法