2017-04-26 165 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"'