Best way to replace multiple characters in a string?

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

    How about this?

    def replace_all(dict, str):
        for key in dict:
            str = str.replace(key, dict[key])
        return str
    

    then

    print(replace_all({"&":"\&", "#":"\#"}, "&#"))
    

    output

    \&\#
    

    similar to answer

提交回复
热议问题