Best way to replace multiple characters in a string?

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

    Maybe a simple loop for chars to replace:

    a = '&#'
    
    to_replace = ['&', '#']
    
    for char in to_replace:
        a = a.replace(char, "\\"+char)
    
    print(a)
    
    >>> \&\#
    

提交回复
热议问题