I'm trying to escape the characters -]\^$*.
each with a single backslash \
.
For example the string: ^stack.*/overflo\w$arr=1
will become:
\^stack\.\*/overflo\\w\$arr=1
What's the most efficient way to do that in Python?
re.escape
double escapes which isn't what I want:
'\\^stack\\.\\*\\/overflow\\$arr\\=1'
I need this to escape for something else (nginx).
Within the square brackets, the individual keys must be double-quoted. The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.
Finally, "\" can be used to escape itself: "\\" is the literal backslash character. There are tons of handy functions that are defined on strings, called string methods.
\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .
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 re escaped = re.escape(a_string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With