Gerard Flanagan wrote:

def replace(s, patt, repls):
    def onmatch(m):
        onmatch.idx += 1
        return repls[onmatch.idx]
    onmatch.idx = -1
    return patt.sub(onmatch, s)


test = """
abcTAG TAG asdTAGxyz
"""

REPLS = [
    'REPL1',
    'REPL2',
    'REPL3',
    ]

print replace(test, re.compile('TAG'), REPLS)

--

or better:

import re

def replace(s, patt, repls):
    repls = iter(repls)
    return patt.sub(lambda m: repls.next(), s)

test = """
abcTAG TAG asdTAGxyz
"""

def repls(tag):
    i = 0
    while True:
        i += 1
        yield tag + str(i)

print replace(test, re.compile('TAG'), repls('REPL'))

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to