简体   繁体   中英

how to insert backslash within double quotes in python

Python: Within a string eg "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"

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"'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM