2017-04-26 130 views
-1

我想用双引号替换所有的单引号,反之亦然。因此,例如,将该字符串"1": " 'me' and 'you'"更改为'1': '"me" and "you"',我该怎么做?如果我做mystering.replace('"', "'")然后将被转换为“,然后,如果我做的这mystering.replace("'", '"')反向,都将被转换为”Python:双字符串替换。

+1

'str.translate' –

+0

我相信你必须使用使用'str.translate' '.replace。替换'仍然会有他认为存在的问题。输出将只是: '“1”:“”我“和”你“”' –

+0

正确。我不明白你为什么要做''“'''?为什么不是'''''? –

回答

6

这是一个很好的用例为string.translate(..)在蟒蛇2.X:!

>>> import string 
>>> print s.translate(string.maketrans('"\'', "'\"")) 
'1': ' "me" and "you"' 
>>> print s 
"1": " 'me' and 'you'" 
1

至于str.translate()(这我会建议)的替代,您可以使用一个dict手动替换每个字符:

>>> repl={'"': "'", "'":'"'} 
>>> oldstr='''"1": " 'me'" and 'you'"''' 
>>> newstr="".join([repl[i] if i in repl else i for i in oldstr]) 
>>> print(oldstr) 
"1": " 'me'" and 'you'" 
>>> print(newstr) 
'1': ' "me"' and "you"'