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
My two cents
a='01ab12ab23ab34ab45ab56ab67ab78ab89ab90';print('The original string: ', a)
sTar = 'ab';print('Look for: ', sTar)
n = 4; print('At occurence #:', n)
sSub = '***';print('Substitute with: ', sSub)
t = 0
for i in range(n):
t = a.find(sTar,t)
print(i+1, 'x occurence at', t)
if t != -1: t+=1
t-=1 #reset, get the correct location
yy = a[:t] + a[t:].replace(sTar, sSub, 1)
print('New string is:', yy)
Output
The original string: 01ab12ab23ab34ab45ab56ab67ab78ab89ab90
Look for: ab
At occurence #: 4
Substitute with: ***
1 x occurence at 2
2 x occurence at 6
3 x occurence at 10
4 x occurence at 14
New string is: 01ab12ab23ab34***45ab56ab67ab78ab89ab90