在 Python 中为 JSON 转义双引号 [英] Escape double quotes for JSON in Python
本文介绍了在 Python 中为 JSON 转义双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中用反斜杠和双引号替换双引号?
<预><代码>>>>s = '我的带有双引号"的字符串blablabla'>>>s.replace('"', '\\"')'我的字符串带有 \\"双引号 \\" blablabla'>>>s.replace('"', '\\\"')'我的字符串带有 \\"双引号 \\" blablabla'我想得到以下内容:
'my string with \"双引号\" blablabla'
解决方案
>>>s = 'my string with \\"双引号\\" blablabla'>>>秒'我的字符串带有 \\"双引号 \\" blablabla'>>>印刷我的字符串带有 \"双引号\" blablabla>>>
当您只要求 's' 时,它会为您转义 \,当您打印它时,您会看到字符串处于更原始"的状态.所以现在...
<预><代码>>>>s = """my string with "双引号"blablabla"""'我的带有双引号"的字符串blablabla'>>>打印 s.replace('"', '\\"')我的字符串带有 \"双引号\" blablabla>>>How can I replace double quotes with a backslash and double quotes in Python?
>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\\"')
'my string with \\"double quotes\\" blablabla'
>>> s.replace('"', '\\\"')
'my string with \\"double quotes\\" blablabla'
I would like to get the following:
'my string with \"double quotes\" blablabla'
解决方案
>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>>
When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...
>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>>
这篇关于在 Python 中为 JSON 转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文