How to escape special characters of a string with single backslashes

PythonNginxEscaping

Python Problem Overview


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).

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

re.escape doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.

When using the repl, try using print to see what is really in the string.

$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>

Solution 5 - Python

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

Solution 6 - Python

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - PythonrlmsView Answer on Stackoverflow
Solution 2 - PythonRy-View Answer on Stackoverflow
Solution 3 - PythonSaguoranView Answer on Stackoverflow
Solution 4 - PythonrjmunroView Answer on Stackoverflow
Solution 5 - PythonAkshay HazariView Answer on Stackoverflow
Solution 6 - PythoncyiningView Answer on Stackoverflow