flexible find and replace ?

Duncan Booth duncan.booth at invalid.invalid
Tue Feb 17 03:18:12 EST 2009


John Machin <sjmachin at lexicon.net> wrote:

> def fancyrepl(tag, replfunc, input_string):
>     count = 0
>     pieces = []
>     pos = 0
>     taglen = len(tag)
>     while 1:
>         try:
>             newpos = input_string.index(tag, pos)
>         except ValueError:
>             pieces.append(input_string[pos:])
>             return ''.join(pieces)
>         pieces.append(input_string[pos:newpos])
>         count += 1
>         pieces.append(replfunc(count))
>         pos = newpos + taglen
> 

Or even:

import re, itertools
def fancyrepl(tag, replfunc, input_string):
	counter = itertools.count(1)
	return re.sub(re.escape(tag),
         lambda m: replfunc(counter.next()), input_string)

which does exactly the same thing in rather less code.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list