flexible find and replace ?

Gerard Flanagan grflanagan at gmail.com
Tue Feb 17 09:49:25 CET 2009


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'))




More information about the Python-list mailing list