flexible find and replace ?

Jason Scheirer jason.scheirer at gmail.com
Mon Feb 16 15:27:54 EST 2009


On Feb 16, 12:10 pm, OdarR <Olivier.Da... at gmail.com> 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,
>
> Olivier

You could split on the string and interleave your new string in
between:

In [1]: def replmaker():
   ...:     index = 0
   ...:     while True:
   ...:         index += 1
   ...:         yield "REPL%02i"%index
   ...:

In [2]: def spliton(string, tag="TAG", sepgen=replmaker):
   ...:     repl_iter = sepgen()
   ...:     strlist = string.split(tag)
   ...:     length = len(strlist)
   ...:     for index, item in enumerate(strlist):
   ...:         yield item
   ...:         if index < length - 1:
   ...:             yield repl_iter.next()
   ...:

In [3]: ''.join(spliton
(".......TAG............TAG................TAG..........TAG....." ))
Out[3]:
'.......REPL01............REPL02................REPL03..........REPL04.....'



More information about the Python-list mailing list