I want to escape a string from this:
str1 = "this is a string (with parentheses)"
to this:
str2 = "this is a string \(with parentheses\)"
That is, a single \
escape character at the parentheses. This is to be fed to another client which needs to escape these characters and will only work with a single escaping slash.
For simplicity I focus below on the opening parentheses only, i.e. changing from '('
to '\('
So far I tried:
replace
str1.replace("(", "\(")
'this is a string \\(with parentheses)'
sub
re.sub( "\(", "\(", str1)
'this is a string \\(with parentheses)'
Escape dictionary with raw string
escape_dict = { '(':r'\('}
"".join([escape_dict.get(char,char) for char in str1])
'this is a string \\(with parentheses)'
Whatever the case I always get double backlash. Is there a way to get only one?
You are confusing the string representation with the string value. The double backslash is there to make the string round-trippable; you can paste the value back into Python again.
The actual string itself has just one backslash.
Take a look at:
>>> '\\'
'\\'
>>> len('\\')
1
>>> print '\\'
\
>>> '\('
'\\('
>>> len('\(')
2
>>> print '\('
\(
Python escapes the backslash in string literal representations to prevent it from being interpreted as an escape code.
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