问题
I am making a function that uses a while True loop to ask the user to input a password that passes the criteria; min8-15max characters in length and includes at least one integer. I am stumped on how to properly check the input for an integer.
My program:
def enterNewPassword():
while True:
pw = input('Please enter a password :')
for i in pw:
if type(i) == int:
if len(pw) >= 8 and len(pw) <= 15:
break
if int not in pw:
print('Password must contain at least one integer.')
if len(pw) < 8 or len(pw) > 15:
print('Password must be 8 and no more than 15 characters in length.')
return pw
回答1:
Try:
if not any(c.isdigit() for c in pw)
Instead of
if int not in pw:
print('Password must contain at least one integer.')
int is a type object and you want check the presence of characters 0-9.
回答2:
You can use regular expressions eg:
import re
password = "hello"
matches = re.findall('[0-9]', password)
if len(matches) < 1:
print "Password must contain at least one integer"
来源:https://stackoverflow.com/questions/33205288/python-check-if-a-string-contains-a-digit