Best way to replace multiple characters in a string?

前端 未结 14 1778
遇见更好的自我
遇见更好的自我 2020-11-22 11:15

I need to replace some characters as follows: &\\&, #\\#, ...

I coded as follows, but I guess there

14条回答
  •  北海茫月
    2020-11-22 11:31

    >>> string="abc&def#ghi"
    >>> for ch in ['&','#']:
    ...   if ch in string:
    ...      string=string.replace(ch,"\\"+ch)
    ...
    >>> print string
    abc\&def\#ghi
    

提交回复
热议问题