I am trying to write a function that returns a string with the nth substring replaced by a new substring:
I tried the following:
import re
from itertools import count
text = "Hello_Dear_Today_is_Nice_Today_is_Nice"
def replace_nth(text, sub, rep_sub, n):
c = count(0)
res = re.sub(r"{}".format(sub), lambda x: rep_sub if next(c) == n else x.group(), text)
return res
replace_nth(text, "Today", "Today_2", 2)
But the returned string is the same, what am I doing wrong?
I am expecting:
Hello_Dear_Today_is_Nice_Today_2_is_Nice
as a result