On Feb 17, 7:18 pm, Duncan Booth <duncan.bo...@invalid.invalid> wrote: > John Machin <sjmac...@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
Not exactly; mine needs taglen = max(1, len(tag)) to stop an infinite loop when len(tag) == 0. > in rather less code. and with rather less execution speed [measured at about half] and rather less OP-explanation speed [guessed] :-) -- http://mail.python.org/mailman/listinfo/python-list