2016-04-23 87 views
0

我必须建立一个你输入密码的程序。密码必须至少包含8个字符,以字母开头,包含大小写字母,无空格和至少两位数字。如何检查一个字符串是否至少包含2位数字并且没有空格?

我拥有一切下来除了最后2

我使用for循环,看看是否有空格或数字尝试过,但如果整个密码由空格或数字只会工作。如果有一个数字或一个空格,如果在错误消息中打印出密码中包含的字符数量,而不仅仅是多少个数字或空格。我知道这是因为for循环发生的,但我坚持如何解决它。

这是我到目前为止有:

if sum(map(str.isdigit, password)) < 2: 

而且,你的检查:

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() 
+0

此外,强制性[XKCD](https://xkcd.com/936/)在讲好密码时。请考虑你是否真的需要大写字母,数字和空格。 –

回答

1
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.') 
1

要在字符串中包含少于2个位数您可以使用报告错误大写和小写字母不正确:

if password.isupper(): 

检查所有字符是否都是大写。要检查是否任何字符被大写,您可以使用:

any(map(str.isupper, password)) 
+0

如果map(lambda x:x.isdigit(),password).count(True)<2'改为'if sum(map(lambda x:x.isdigit(),password))> = 2' - 它适用于Python 2和Python 3,你的版本不适用于Python 3 – MaxU

+0

谢谢,看起来更好。 –

0

“(......)没有空间和至少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 
相关问题