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
print(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
Without any deps, certainly a lot faster than re/itertools. If the string contains the substring n times, the number resulting from the split must be n+1 . If that is not the case, the function returns None
def replace_nth(text, sub, rep_sub, n):
return (sub.join(g[:n]) + rep_sub + g[n]) if len(g:=text.split(sub,maxsplit=n))==n+1 else None
text = "Hello_Dear_Today_is_Nice_Today_is_Nice"
print(replace_nth(text, "Today", "Today_2", 2))