user1778824
user1778824

Reputation: 369

how to insert backslash within double quotes in python

Python: Within a string e.g. "Hi"5"Hello" I want to insert (backslash) in front of double quotes. For the above example I want to insert "Hi\"5\"Hello". Is there some way to do so in python.

I have data of the form:

   <a> <b> "Hi"5"Hello"
   <c> <d> ""Way"toGo"

I want to convert this data to the form:

   <a> <b> "Hi\"5\"Hello"
   <c> <d> "\"Way\"toGo"

Upvotes: 0

Views: 241

Answers (2)

Chris Johnson
Chris Johnson

Reputation: 22026

It's easy to get lost in character-escaping rules especially if you're flipping between Python, JavaScript, regex syntaxes etc. The easy way to do this in Python is to flag your string as "raw" using "r" notation:

Bad example:

>>> test = 'Hi \there \\friend \n good day'
>>> print test
Hi      here \friend 
 good day

Good example:

>>> test = r'Hi \there \\friend \n good day'
>>> print test
Hi \there \\friend \n good day

Upvotes: 0

mgilson
mgilson

Reputation: 310287

If I understand correctly, you want to escape all but the first and last " in the string. If that's true, then we get something like:

>>> i1 = s.index('"')
>>> i2 = s.rindex('"')
>>> i1
0
>>> i2
11
>>> s[i1+1:i2]
'Hi"5"Hello'
>>> ''.join((s[:i1+1],s[i1+1:i2].replace('"',r'\"'),s[i2:]))
'"Hi\\"5\\"Hello"'

Upvotes: 2

Related Questions