Python Team Python Team - 7 months ago 26
Python Question

String replace without replacing the first instance

I have a string and I want to replace

every time after its second occurrence only.

s = "change the string in the sentence and the save"

I would like the replace the word
. But except the first one.

Output should be:

change the string in hello sentence and hello save


I would split the string from right with the word you're going to replace use str.rsplit() function, but only split s.count('the') - 1 times.

Then, join the output list with hello:

>>> s.rsplit('the', s.count('the') - 1)
['change the string in ', ' sentence and ', ' save']

>>> 'hello'.join(s.rsplit('the', s.count('the') - 1))
'change the string in hello sentence and hello save'