Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping characters in python just once (single backlash)

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:

  1. replace

    str1.replace("(", "\(")
    'this is a string \\(with parentheses)'
    
  2. sub

    re.sub( "\(", "\(", str1)
    'this is a string \\(with parentheses)'
    
  3. 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?

like image 697
atineoSE Avatar asked Oct 20 '25 02:10

atineoSE


1 Answers

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.

like image 152
Martijn Pieters Avatar answered Oct 21 '25 14:10

Martijn Pieters