需要将'
替换为\'
但那就是我得到的:
>>> 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"
结果?
答案 0 :(得分:4)
你已经把它弄好了,但是repr
字符串的表示让你失望了。尝试:
print s.replace("'", "\\'")
=> It\'s nice to have an example
如果您不使用print
,则会显示结果字符串的repr
(而不是str
),并且在此repr
中,反斜杠会被转义结果是双反斜杠。
请参阅this question,关于__str__
和__repr__
。
编辑 - 因为您在评论中提到需要一个字符串,您可以在javascript中使用...
使用json.dumps()代替repr
。
答案 1 :(得分:1)
您可以将encode
与string-escape
编码一起使用:
>>> s = "It's nice to have an example"
>>> s = s.encode('string-escape')
>>> print s
It\'s nice to have an example