Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python

前端 未结 2 1642
夕颜
夕颜 2021-01-17 05:56

I have a dictionary with the strings to be replaced as keys and its replacement as values. Other than looking through the stri

2条回答
  •  梦谈多话
    2021-01-17 06:07

    re.sub can call a function that returns the substitution

    segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
    sentence = "this is a foobar in a barbar withoutspace"
    
    import re
    
    def fn(match):
        return segmenter[match.group()]
    
    print re.sub('|'.join(re.escape(k) for k in segmenter), fn, sentence)
    

提交回复
热议问题