Python Team Python Team - 1 year ago 95
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

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download