I want to replace the n\'th occurrence of a substring in a string.
There\'s got to be something equivalent to what I WANT to do which is
mystring.repl
I've tweaked @aleskva's answer to better work with regex and wildcards:
import re
def replacenth(string, sub, wanted, n):
pattern = re.compile(sub)
where = [m for m in pattern.finditer(string)][n-1]
before = string[:where.start()]
after = string[where.end():]
newString = before + wanted + after
return newString
replacenth('abdsahd124njhdasjk124ndjaksnd124ndjkas', '1.*?n', '15', 1)
This gives abdsahd15jhdasjk124ndjaksnd124ndjkas. Note the use of ? to make the query non-greedy.
I realise that the question explicitly states that they didn't want to use regex, however it may be useful to be able to use wildcards in a clear fashion (hence my answer).