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 refrom itertools import counttext = "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 resprint(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