如何在Python中将单引号替换为反斜杠+单引号

时间:2014-03-10 21:14:01

标签: python regex replace

需要将'替换为\' 但那就是我得到的:

>>> 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"结果?

2 个答案:

答案 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)

您可以将encodestring-escape编码一起使用:

>>> s = "It's nice to have an example"
>>> s = s.encode('string-escape')
>>> print s
It\'s nice to have an example