1. 程式人生 > >同時替換掉多個字符串

同時替換掉多個字符串

pan png ole text group color repl spa ace

基礎沒學牢,看到一篇大神的文章,http://blog.csdn.net/huludan/article/details/50925735 同時替換多個字符串

import re  
def multiple_replace(text, adict):  
    rx = re.compile(|.join(map(re.escape, adict)))  
    def one_xlat(match):  
        return adict[match.group(0)]  
    return rx.sub(one_xlat, text) 

text = "Larry Wall is the creator of Perl
" adict = { "Larry Wall" : "Guido van Rossum", "creator" : "Benevolent Dictator for Life", "Perl" : "Python", } print multiple_replace(text, adict)

技術分享圖片

同時替換掉多個字符串