在python中用'\"'替换双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41970582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace double quotes with '\"' in python
提问by McGrady
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\"}
?
如何转换{\"a\": \"1\", \"b\": \"2\"}
?
回答by McGrady
Try this:
尝试这个:
print l.replace('"','\"')
'\"'
doesn't mean anything special to Python, so you needn't to add \
before "
,if you run
'\"'
对 Python 没有什么特别的意义,所以你不需要\
在之前添加"
,如果你运行
print l.replace('\"', '\\"')
,you will get a single backslash too.
print l.replace('\"', '\\"')
, 你也会得到一个反斜杠。
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.
实际上你看到的是字符串的表示,它是通过repr() 方法添加的。Python表示字符串中\\
的反斜杠,因为反斜杠是一个转义字符。
If you print it, you will get single backslash.
如果你打印它,你会得到一个反斜杠。
You can see more information from String and Bytes literals.
您可以从String 和 Bytes 文字中看到更多信息。
回答by Avinash
You can try this also
你也可以试试这个
print l.replace('"',r'\"')
or
或者
print l.replace('"','\"')