How to escape special characters of a string with single backslashes How to escape special characters of a string with single backslashes python python

How to escape special characters of a string with single backslashes


This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",                                          "]":  r"\]",                                          "\\": r"\\",                                          "^":  r"\^",                                          "$":  r"\$",                                          "*":  r"\*",                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import reescaped = re.escape(a_string)


Just assuming this is for a regular expression, use re.escape.


We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr