Reputation: 11
I am doing a password checker, I have specified the users can use these 3 special characters only ($,&,!) special = ['$', '&', '!'] But when I typed # and the output is still True I have tried to use isdight and isalpha,
if not any(char in special for char in password):
return ('False')
val = False
if not password.isdigit():
return('False')
val = False
if not password.isalpha():
return('False')
val = False
But the situation is different, when I specify the 3 special characters $,&,! and i type one of them i.e. $ , the output is still False , same as other special characters that are not approved, so what should I do next?
Upvotes: 0
Views: 7222
Reputation: 44213
This can also be done with a regular expression:
[A-Za-z0-9$&!]+$
[A-Za-z0-9$&!]+
Matches any upper or lower case character in the range A-Z or any digit or $
or &
or !
one or more times.$
matches the end of the string (the re.match
function implicitly matches the start of the string).The code:
import re
def test_password(password):
# use the following statement if you really want to return a string
# return 'True' if re.match('[A-Za-z0-9$&!]+$', password) else 'False'
return True if re.match('[A-Za-z0-9$&!]+$', password) else False
print(test_password('abC1!'))
print(test_password(''))
print(test_password('abC1#'))
Prints:
True
False
False
If you would rather
Upvotes: 0
Reputation: 658
I'm assuming you are asking how to check if all characters are either:
Your code is checking each of these three separately, which means you are testing first that ALL characters are one of the special ones, then that ALL characters are normal letters, then finally that ALL are numbers. Naturally, this will never be the case, as a digit can't also be a letter and a special character all at once.
To fix this, you need to use or
, which will check if any of your conditions is True. You also need to change the not any(...)
to an not all(...)
so that it will fail when there's a single error and not only when ALL characters fail our conditions. You can combine steps 2 and 3 into one by using str.isalnum()
if all(char in special or char.isalnum() for char in password):
val = False
return "False" # did you mean to return a string here?
Upvotes: 0
Reputation: 2090
I think you want your code to look something like this:
special_chars = ['$', '&', '!']
password = input("Provide your password: ")
invalid = False
for char in password:
if char not in special_chars:
print('Invalid char found! Use only: {}'.format(special_chars))
invalid = True
break
if not invalid:
print('Valid password.')
I just used print statements as I am not sure how this integrates into your existing code. To explain, all you need to do is check that every character in the password is in the list of special characters that you allow. No need for multiple checks.
Upvotes: 1