【发布时间】:2014-03-10 21:14:01
【问题描述】:
需要将'替换为\'
但这就是我得到的:
>>> s = "It's nice to have an example"
>>> s.replace("'", "\\'")
"It\\'s nice to have an example"
>>> s.replace("'", "\'")
"It's nice to have an example"
>>> s.replace("'", "\\\'")
"It\\'s nice to have an example"
如何得到"It\'s nice to have an example"的结果?
【问题讨论】:
-
你做对了。 Python 正在转义
` again when it displays it, but the string itself is correct. Tryprint`ing 值,您会正确看到它。 -
如果你想看看字符串打印时的样子...你为什么不print呢?请注意,交互式解释器不打印字符串,它显示它的字符串表示形式(即它相当于
print(repr(text)),注意额外的repr)。 -
我只需要转义单个 qoute 并且我想在 repr 中获得单个反斜杠。因为当我序列化时,我得到了我的 javascript 代码:
SmObj.initialize('[{"description": "My belgian sheepdog! Isn\\'t she cute?", "author": {"username": "Marabesta", "get_full_name": "Olga Smith"}, {...}, ...]');