(This answer should be as a comment to @Padraic Cunningham, but I don't have the "points" yet to do so, so I can only post a new reply)
The solution provided by Padraic Cunningham is simple and works, except for the bug mentioned by @Haider.
To fix the bug, there is an easier solution than the one provided by Haider: Change the way the value of i
is updated. It should not be incremented if the searched string has not been found.
Additionally, there is a bug if n
is smaller than 1 (should not happen, but probably better to check).
The very slightly modified solution is thus:
def nth_repl(s, sub, repl, n):
if n < 1:
return s
find = s.find(sub)
# If find is not -1 we have found at least one match for the substring
i = find != -1
# loop util we find the nth or we find no match
while find != -1 and i != n:
# find + 1 means we start searching from after the last match
find = s.find(sub, find + 1)
#i += 1 => This is wrong, as might not have found it
i += find != -1
# If i is equal to n we found nth match so replace
if i == n:
return s[:find] + repl + s[find+len(sub):]
return s