Best way to replace multiple characters in a string?

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

    Here is a python3 method using str.translate and str.maketrans:

    s = "abc&def#ghi"
    print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))
    

    The printed string is abc\&def\#ghi.

提交回复
热议问题