我必須建立一個你輸入密碼的程序。密碼必須至少包含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()
此外,強制性[XKCD](https://xkcd.com/936/)在講好密碼時。請考慮你是否真的需要大寫字母,數字和空格。 –