将'替换为'到字符串中

时间:2013-03-04 07:22:50

标签: python replace

我有一个字符串

s = r"This is a 'test' string"

我正在尝试将'替换为',因此字符串将如下所示

s = r"This is a \'test\' string"

我尝试了s.replace("'","\'"),但结果没有变化。它保持不变。

3 个答案:

答案 0 :(得分:8)

"\'"仍然与"'"相同 - 你必须逃避反斜杠。

mystr = mystr.replace("'", "\\'")

将其设为原始字符串r"\'"也可以。

mystr = mystr.replace("'", r"\'")

另请注意,永远不要使用str(或任何其他内置名称)作为变量名称,因为它会覆盖内置函数,并且在您尝试使用内置函数时可能会引起混淆。

>>> mystr = "This is a 'test' string"
>>> print mystr.replace("'", "\\'")
This is a \'test\' string
>>> print mystr.replace("'", r"\'")
This is a \'test\' string

答案 1 :(得分:6)

你必须逃避“\”:

str.replace("'","\\'")

“\”是一个转义序列指示符,用作普通字符,必须自行转义。

答案 2 :(得分:2)

>>> str = r"This is a 'test' string"
>>> print str
This is a 'test' string
>>> str.replace("'","\\'")
"This is a \\'test\\' string"

您需要转义特殊字符\