How to Escape Special Characters of a Python String with a Single Backslash?

The backslash escape character '\' is a special Python string character that is usually followed by an alphabetic character. For example, the tabular whitespace '\t' and newline '\n'. In regular expressions, you can use the single escape to remove the special meaning of regex symbols. For example, to match the dot or asterisk characters '.' and '*', you must first get rid of the special meanings of the regex dot . or regex asterisk * operators by escaping them with \. or \*.

Problem Formulation

Say, you want to escape the characters -]\^$*. with a single backslash \.

For example, the string 'hello-[world]-$100' should be transformed to:

'hello\-\[world\]\-\$100'

How to accomplish this in Python?

Method: re.escape()

The most straightforward way to escape a special regex character is with the re.escape() function escapes all special regex characters with a double backslash, such as the asterisk, dot, square bracket operators.

>>> import re
>>> re.escape('hello-[world]-$100')
'hello\\-\\[world\\]\\-\\$100'

If you really need to escape with a single backslash instead of the double backslash, you can do the following method.

Background Regex Escape

Method: String Translate Table

The str.translate(table) method returns a translated string that is a copy of the original string whereas only the character translations defined in the table argument have been applied to the string. The table is supposed to be an object that implements the __getitem__() dunder method—in our case obtained with the str.maketrans() function. In most cases, a dictionary is the perfect data structure for this because it allows you to map one character to anotherโ€”intuitively, what you want to do when translating a string into another one.

s = 'hello-[world]-$100'
table = str.maketrans({"-":  r"\-", "]":  r"\]", "\\": r"\\",
                       "^":  r"\^", "$":  r"\$", "*":  r"\*", ".":  r"\."})

# Replace string
s_new = s.translate(table)
print(s_new)
# hello\-[world\]\-\$100