I've been asked to create a program that identifies if a password is valid or not. The one part I am struggling with is identifying whether there are two of the same character adjacent to each other. Help would be appreciated and here is the program so far:
import re
pswrd = input("Enter Desired Password:")
if len(pswrd) < 6:
print("Password must have more than 6 characters.")
if len(pswrd) > 15:
print("Password must have no more than 15 characters.")
if re.search("[$#@]",pswrd):
print("Password must have no special characters.")
if not re.search("[0-9]",pswrd):
print("Password must contain a number.")
if not re.search("[a-z]",pswrd):
print("Password must contain a lower case letter.")
if not re.search("[A-Z]",pswrd):
print("Password must contain an upper case letter.")
To check if two strings have the same characters:Use the sorted() function to sort the two strings. Use the equality operator to compare the results. If the comparison evaluates to True , the two strings have the same characters.
Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.
The regex to check for adjacent characters is
(.)\1
The period (.) matches any character. The brackets create a capturing group around that character, which is then referenced by \1.
So, the condition would be:
if re.search(r"(.)\1", pswrd)
Note the r character before the regular expression. This makes it a raw string. Regular expressions should always be made raw strings. This ensures that certain special characters in the regex (like \b) are not interpreted before being passed to the re module.
You can test the regular expression here: http://regexr.com/3h0g0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With