paragraph = ( "This example is an example on how to make an example with the" " word example. the example ends here with an example. for example" ) target = "example" def replace_occurence_count(paragraph: str, target: str) -> str: occurances = paragraph.count(target) for number in range(1, occurances + 1): paragraph = paragraph.replace(target, f"{number}", 1) return paragraph print(replace_occurence_count(paragraph, target))
Output:This 1 is an 2 on how to make an 3 with the word 4. the 5 ends here with an 6. for 7
@bowlofred
For a simple counter, you can use itertools count
from itertools import count counter = count(1) print(next(counter)) print(next(counter))
Output:1
2