2013-03-04 35 views
3

我有一个字符串替换一个atring

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

我试图取代“到\”这样的字符串像下面

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

我试图s.replace("'","\'"),但“到\”有结果没有变化。它仍然是一样的。

+2

如果输入字符串为'R“这是已经包含了‘测试’字符串\‘转义引号\’”'? – 2013-03-04 07:26:44

+1

顺便说一句:你不应该使用'str'作为名字。这是一个内置的名称。 – 2013-03-04 07:28:39

回答

4

你必须逃脱“\”:

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

“\”是转义序列指示符,其中,要使用作为一个正常的焦炭,必须被转义(通过)本身。

+0

如果您在输出中看到'\\'',请参阅本文。https://stackoverflow.com/questions/17300917/replace-a-character-with-backslash-bug-python – 2017-11-03 12:08:09

6

"\'"仍然与"'"相同 - 您必须避开反斜线。

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 
2
>>> str = r"This is a 'test' string" 
>>> print str 
This is a 'test' string 
>>> str.replace("'","\\'") 
"This is a \\'test\\' string" 

你需要躲避特殊字符\