flexible find and replace ?

Gerard Flanagan grflanagan at gmail.com
Tue Feb 17 03:17:41 EST 2009


OdarR wrote:
> Hi guys,
> 
> how would you do a clever find and replace, where the value replacing
> the tag
> is changing on each occurence ?
> 
> ".......TAG............TAG................TAG..........TAG....."
> 
> is replaced by this :
> 
> ".......REPL01............REPL02................REPL03..........REPL04..."
> 
> 
> A better and clever method than this snippet should exist I hope :
> 
> counter = 1
> while 'TAG' in mystring:
>     mystring=mystring.replace('TAG', 'REPL'+str(counter), 1)
>     counter+=1
>     ...
> 
> (the find is always re-starting at the string beginning, this is not
> efficient.
> 
> any ideas ? thanks,
> 

The first thing that comes to mind is re.sub:

import re

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)




More information about the Python-list mailing list