Best way to replace multiple characters in a string?

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

    advanced way using regex

    import re
    text = "hello ,world!"
    replaces = {"hello": "hi", "world":" 2020", "!":"."}
    regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
    print(regex)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题