I have a file like this (this is a simplified version):
james sfsf qef qef
qef qef qe fff
qqew james james qef
qefq ffgrsf wsef
qef james eq james
I want to replace each iteration of 'james' with a different value. Here's what I have in my test code:
f=open('file_to_be_read.txt','r')
text=f.read()
matches=len(re.findall('james',text))
f.close()
number=0
for x in range(matches):
new_text=re.sub(r'james',str(number),text,count=1)
number+=1
r=open('result_file.txt','w')
r.write(new_text)
r.close()
But it just replaces the first 'james' with 2. Rather than produce the following result that I want:
1 sfsf qef qef
qef qef qe fff
qqew 2 3 qef
qefq ffgrsf wsef
qef 4 eq 5
I thought that by repeating the re.sub with count=1 I would replace 1 james each time but allow me to change the replace value.