We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Searching and Replacing

July 13, 2002

The string replace method

Describe string.replace here..

Using regular expression substitutions

Describe re.sub here. Move stuff from this page.

Mapping strings through translation tables

Describe string.translate here.

Replacing multiple strings

Replace multiple string pairs in one go (File: MultiReplace.py)
import re, string

class MultiReplace:

    def __init__(self, repl_dict):
        # "compile" replacement dictionary

        # assume char to char mapping
        charmap = map(chr, range(256))
        for k, v in repl_dict.items():
            if len(k) != 1 or len(v) != 1:
                self.charmap = None
            charmap[ord(k)] = v
            self.charmap = string.join(charmap, "")

        # string to string mapping; use a regular expression
        keys = repl_dict.keys()
        keys.sort() # lexical order
        keys.reverse() # use longest match first
        pattern = string.join(map(re.escape, keys), "|")
        self.pattern = re.compile(pattern)
        self.dict = repl_dict

    def replace(self, str):
        # apply replacement dictionary to string
        if self.charmap:
            return string.translate(str, self.charmap)
        def repl(match, get=self.dict.get):
            item = match.group(0)
            return get(item, item)
        return self.pattern.sub(repl, str)

r = MultiReplace({"spam": "eggs", "eggs": "spam"})
print r.replace("spam&eggs") # prints "eggs&spam"

r = MultiReplace({"a": "b", "b": "a"})
print r.replace("keaba") # "kebab"

r = MultiReplace({". ": "\n", "!": "exclamation", "?": "question"})
print repr(r.replace("look. an albatross !")) # 'look\nan albatross exclamation'