Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape special characters of a string with single backslashes

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

like image 982
Tom Avatar asked Sep 21 '13 17:09

Tom


People also ask

How do you escape a backslashes string?

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.

How do you escape backslashes in Python?

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.

How do you escape a character in a string?

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


1 Answers

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) 
like image 148
rlms Avatar answered Oct 02 '22 14:10

rlms