I'm writing a function that checks multiple conditions for a string (a "password"). This string has to be between 6 and 20 characters long, must have at least one number, must have special characters AND must have at least two uppercase letters.
This is where I ran into problems because I'm using RegEx and I can't get the "must have two uppercase letters" part to work, everything else works fine.
import re
password = input("Input password: ")
def valid_pw(password):
valid = True
if not re.search(',{6,20}', password):
valid = False
if not re.search('[0-9]', password):
valid = False
if not re.search('[A-Z].*[A-Z]', password):
valid = False
if not re.search('[$& ,:;=?@#|<>.^*()%!-]', password):
valid = False
return valid
print(password, "is valid: ", valid_pw(password))
The third "if" statement is my attempt at checking for two uppercase letters but doesn't work as expected. If the input is password: AbC.123 the output should be "AbC.123 is valid: True" since it checks every condition, yet I'm still getting "False" due to the two uppercase part.
CodePudding user response:
None of your checks require regular expressions to implement.
def valid_pw(password):
if not 6 <= len(password) <= 20:
return False
if not any(c.isdigit() for c in password):
return False
if sum(c.isupper() for c in password) < 2:
return False
if not any(c in '[$& ,:;=?@#|<>.^*()%!-]' for c in password):
return False
return True
Notice that once any of the conditions returns False
, you can stop searching: the password won't become true after that.
In your original formulation, elif
would be preferable to if
for all the latter clauses. Also, the symbol .
means "any character", not ,
. Your checks were likely failing due to that, and not the capitalization check. You may have failed to realize that because all the checks were running instead of terminating early.
CodePudding user response:
A slight improvement to your code snippet would be to start with a 'false' and then check for each condition consequently and finally set the valid to 'true'. You can use regex search for special characters and numbers.
Use len()
for checking the length parameter, and in a loop (one liner is good) check for upper case in the string (ie looping through every character of the string).
Working code below.
import re
password_str = "Abc@123"
def validate_pw(pwd):
valid = False
if len(pwd) > 6 & len(pwd) <= 20:
if re.search(r'\d', pwd):
regexp = re.compile('[^0-9a-zA-Z] ')
if regexp.search(pwd):
if (any(x.isupper() for x in pwd)):
valid = True
print(valid)
validate_pw(password_str)