Iterative find/replace from a list of tuples in Python

前端 未结 5 1604
走了就别回头了
走了就别回头了 2020-12-17 05:37

I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this

5条回答
  •  抹茶落季
    2020-12-17 05:55

    Same answer as mhawke, enclosed with method str_replace

    def str_replace(data, search_n_replace_dict):
        import re
        REPLACEMENTS = search_n_replace_dict
    
        def replacer(m):
            return REPLACEMENTS[m.group(0)]
    
        r = re.compile('|'.join(REPLACEMENTS.keys()))
        return r.sub(replacer, data)
    

    Then we can call this method with example as below

    s = "abcd abcd efgh efgh;;;;;; lkmnkd kkkkk"
    d = dict({ 'abcd' : 'aaaa', 'efgh' : 'eeee', 'mnkd' : 'mmmm' })
    
    
    print (s)
    print ("\n")
    print(str_replace(s, d))
    

    output :

    abcd abcd efgh efgh;;;;;; lkmnkd kkkkk
    
    
    aaaa aaaa eeee eeee;;;;;; lkmmmm kkkkk
    

提交回复
热议问题