Check if string contains special characters in python

I want to check if the password contains special characters. I have searched for some examples but cannot find as to my problem. How should I do it? This is how I do it so far;

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


My string is password.


source to share

2 answers

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

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


The quote was hidden in the line. This means you create a set containing all your invalid characters, then navigate to it and password

(in other words, a set containing all the unique characters that exist in both the set and the password string). If there is no match, the result set will be empty and therefore evaluated as False

, otherwise it will evaluate as True

and print the message.



Certain characters in a special character string have special meaning in regular expressions and must be escaped. You get a syntax error because you included "

in the middle of the line denoted by double quotes, so Python ends up processing the line there and then chokes on the garbage it sees afterwards. Try the following:

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


I used a string literal, which you should always use in regular expressions. I avoided the characters that needed to be escaped and simplified your expression a bit, since the beginning ^

and end of $

string markers are not required - once one match is made, it will return True and skip the next code.

If in doubt, run away :)



All Articles