import re


class Replacer(object):

    def __init__(self, **replacements):
        self.replacements = replacements
self.locator = re.compile('|'.join(re.escape(s) for s in replacements))

def _doreplace(self, mo):
    return self.replacements[mo.group()]

def replace(self, s):
    return self.locator.sub(self._doreplace, s)
Efficiently carry out multiple string replacements in Python