You can use the while loop with str.find to find the nth occurrence, if it exists, and use this position to create a new line:
def nth_repl(s, sub, repl, nth): find = s.find(sub)
Example:
In [14]: s = "foobarfoofoobarbar" In [15]: nth_repl(s, "bar","replaced",3) Out[15]: 'foobarfoofoobarreplaced' In [16]: nth_repl(s, "foo","replaced",3) Out[16]: 'foobarfooreplacedbarbar' In [17]: nth_repl(s, "foo","replaced",5) Out[17]: 'foobarfoofoobarbar'
source share