flexible find and replace ?
John Machin
sjmachin at lexicon.net
Mon Feb 16 21:27:16 EST 2009
On Feb 17, 7:10 am, 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,
C:\junk>type fancyrepl.py
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
tests = [
'',
'XXX',
'XXXXXX',
'abcdeXXX',
'XXXfghij',
'abcdeXXXfghij',
'abcdeXXXfghijXXXpqrst',
]
for test in tests:
print ' <', repr(test)
result = fancyrepl('XXX', lambda n: 'SUB%d' % n, test)
print ' >', repr(result)
C:\junk>fancyrepl.py
< ''
> ''
< 'XXX'
> 'SUB1'
< 'XXXXXX'
> 'SUB1SUB2'
< 'abcdeXXX'
> 'abcdeSUB1'
< 'XXXfghij'
> 'SUB1fghij'
< 'abcdeXXXfghij'
> 'abcdeSUB1fghij'
< 'abcdeXXXfghijXXXpqrst'
> 'abcdeSUB1fghijSUB2pqrst'
HTH,
John
More information about the Python-list
mailing list