fork download
  1. import re
  2.  
  3. text = "Hello_Dear_Today_is_Nice_Today_is_Nice"
  4.  
  5. def replace_nth(text, sub, rep_sub, n):
  6. if n > 1:
  7. sub = rf'^(.*(?:{sub}.*?){{{n - 1}}}){sub}'
  8. rep_sub = r'\1' + rep_sub
  9. return re.sub(sub, rep_sub, text, count=1)
  10.  
  11. print(replace_nth(text, "Today", "Today_2", 2))
Success #stdin #stdout 0.03s 9788KB
stdin
Standard input is empty
stdout
Hello_Dear_Today_is_Nice_Today_2_is_Nice