Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string contains special characters in python

I want to check if a password contains special characters. I have googled for a few examples but cant find that addresses my problem. How do I do it? Here is how I am trying it so far;

elif not re.match("^[~!@#$%^&*()_+{}":;']+$",password)
        print "Invalid entry."
        continue

My string is password.

like image 740
mungaih pk Avatar asked Feb 12 '23 22:02

mungaih pk


1 Answers

You don't need a regex for this. Try:

elif set('[~!@#$%^&*()_+{}":;\']+$').intersection(password):
    print "Invalid entry."

The quotation mark has been escaped in the string. What this does is create a set containing all your invalid characters, then take the intersection of it and password (in other words, a set containing all unique characters that exist in both the set and the password string). If there are no matches, the resulting set will be empty, and thus evaluate as False, otherwise it will evaluate as True and print the message.

like image 119
Silas Ray Avatar answered Feb 14 '23 14:02

Silas Ray