Best way to replace multiple characters in a string?

前端 未结 14 1993
遇见更好的自我
遇见更好的自我 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:40

    Simply chain the replace functions like this

    strs = "abc&def#ghi"
    print strs.replace('&', '\&').replace('#', '\#')
    # abc\&def\#ghi
    

    If the replacements are going to be more in number, you can do this in this generic way

    strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
    print "".join([replacements.get(c, c) for c in strs])
    # abc\&def\#ghi
    

提交回复
热议问题