Best way to replace multiple characters in a string?

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

    You may consider writing a generic escape function:

    def mk_esc(esc_chars):
        return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
    
    >>> esc = mk_esc('&#')
    >>> print esc('Learn & be #1')
    Learn \& be \#1
    

    This way you can make your function configurable with a list of character that should be escaped.

提交回复
热议问题