Escape special characters in a Python string


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.*$"))
>>> re.escape("")
>>> print(re.escape(""))

Repeating it here:


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.