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 use simple function, which lists all occurrences, picks the nth one's position and uses it to split original string into two substrings. Then it replaces first occurrence in the second substring and joins substrings back into the new string:
import re
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted, 1)
newString = before + after
print(newString)
For these variables:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
outputs:
ababababCDabababab
Notes:
The
wherevariable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with0usually, not with1. Therefore there is an-1index andnvariable is the actual nth substring. My example finds 5th string. If you usenindex and want to find 5th position, you'll neednto be4. Which you use usually depends on the function, which generates ourn.
This should be the simplest way, but maybe it isn't the most Pythonic way, because the
wherevariable construction needs importingrelibrary. Maybe somebody will find even more Pythonic way.
Sources and some links in addition:
whereconstruction: How to find all occurrences of a substring?- string splitting: https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string
- similar question: Find the nth occurrence of substring in a string