I have a string which contains multiple Q =
and the goal is to add the number of occurance after each Q
.
For example, 'Q = 1 t h \n Q = 2 t h \n Q = 3 t h'
should be 'Q1 = 1 t h \n Q2 = 2 t h \n Q3 = 3 t h'
Here's my method:
import re
test = 'Q = 1 t h \n Q = 2 t h \n Q = 3 t h'
num = test.count('Q =')
pattern = re.compile('[Q]')
for n in range(num):
where = [m for m in pattern.finditer(test)]
test = test[:where[n].start()+1]+f'{n+1}'+test[where[n].start()+1:]
print(test)
Is there any better solution?