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

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.