Best way to replace multiple characters in a string?

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

    Using reduce which is available in python2.7 and python3.* you can easily replace mutiple substrings in a clean and pythonic way.

    # Lets define a helper method to make it easy to use
    def replacer(text, replacements):
        return reduce(
            lambda text, ptuple: text.replace(ptuple[0], ptuple[1]), 
            replacements, text
        )
    
    if __name__ == '__main__':
        uncleaned_str = "abc&def#ghi"
        cleaned_str = replacer(uncleaned_str, [("&","\&"),("#","\#")])
        print(cleaned_str) # "abc\&def\#ghi"
    

    In python2.7 you don't have to import reduce but in python3.* you have to import it from the functools module.

提交回复
热议问题