Escape special characters in a Python string

StackOverflow

Does Python have a function that I can use to escape special characters in a string?

For example, I"m "stuck" : should become I"m "stuck" :.

Answer rating: 223

Use re.escape

>>> import re
>>> re.escape(r" a.*$")
"\ a.*$"
>>> print(re.escape(r" a.*$"))
 a.*$
>>> re.escape("www.stackoverflow.com")
"www.stackoverflow.com"
>>> print(re.escape("www.stackoverflow.com"))
www.stackoverflow.com

Repeating it here:

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

As of Python 3.7 re.escape() was changed to escape only characters which are meaningful to regex operations.





Tutorials