Best way to replace multiple characters in a string?

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

    Are you always going to prepend a backslash? If so, try

    import re
    rx = re.compile('([&#])')
    #                  ^^ fill in the characters here.
    strs = rx.sub('\\\\\\1', strs)
    

    It may not be the most efficient method but I think it is the easiest.

提交回复
热议问题