replacing all 'rng's in a buffer with consecutive r[1], r[2]'s

m g william mgbg25171 at
Wed Oct 4 13:49:22 CEST 2006

I read a file into a buffer and subject it to re.sub()
I can replace every occurrence of a pattern with a fixed string but when
I try to replace each occurrence with a string that changes (by having
an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note
that the incrementing number generator function, I'm calling in
re.sub(), (which works fine outside it), seems to be evaluated only once
and is therefore not incrementing the number.

Can someone please show me a working eg of how to replace 'rng' in a
file with 'r[1]', 'r[2]' etc. This is my first Python program so any
help would be very gratefully received.

Here's my code

#read orig file into buf & close file
import re
infile = file('pyInfile', 'r')
buf =
print buf

#replace all allocated streams with 'rng'
print '=========== orig buf ============'; print buf
pat = re.compile('r\[\d+\]')
buf = pat.sub("rng", buf, 0)

#now replace all 'rng's with consecutive streams
def static_num():
    ''' this is a generator function that avoids globals
yield differentiates fn as generator fn which freezes
    x = 0
    while True:
       x += 1
       yield str(x)

static = static_num().next

pat = re.compile('rng')
#there is a problem in that static only seems to get called once.
#need to invoke this every time you get a match for it to
buf = pat.subn('rng[' + static() + ']', buf, 0)
print 'static() incrementing ok ' + static()
print 'static() incrementing ok ' + static()
print '=========== changed to ============'; print buf[0] 
#outfile = file('pyOutfile', 'w')

More information about the Python-list mailing list