I have a string -
l = '{"a": "1", "b": "2"}'
I want to convert this string to -
'{\"a\": \"1\", \"b\": \"2\"}'
For this I am trying to replace " with \\"
Here's what I have tried -
l.replace('\"', '\"')
'{"a": "1", "b": "2"}'
l.replace('\"', '\\"')
'{\\"a\\": \\"1\\", \\"b\\": \\"2\\"}'
How do I convert {\\"a\\": \\"1\\", \\"b\\": \\"2\\"}
?
Try this:
print l.replace('"','\\"')
'\\"'
doesn't mean anything special to Python, so you needn't to add \\
before "
,if you run
print l.replace('\\"', '\\\\"')
,you will get a single backslash too.
Actually what you are seeing is the representation of the string, it's added by repr () method.Python represents backslashes in strings as \\\\
because the backslash is an Escape Character .
If you print it, you will get single backslash.
You can see more information from String and Bytes literals .
You can try this also
print l.replace('"',r'\"')
or
print l.replace('"','\\"')
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.