How to replace all occurrences except the first?

How to replace all repeating words except the first in a line? That is, these lines

s='cat WORD dog WORD mouse WORD'
s1='cat1 WORD dog1 WORD'

will be replaced by

s='cat WORD dog REPLACED mouse REPLACED'
s1='cat1 WORD dog1 REPLACED'

I cannot replace the line back because I do not know how many times the word occurs in each line. I figure out a cool way:

temp=s.replace('WORD','XXX',1)
temp1=temp.replace('WORD','REPLACED')
ss=temp1.replace('XXX','WORD')

But I want more pythonic method. Do you have any ideas?

+4
source share
1 answer

Use string.countwithrreplace

>>> def rreplace(s, old, new, occurrence):
...     li = s.rsplit(old, occurrence)
...     return new.join(li)
... 
>>> a
'cat word dog word mouse word'
>>> rreplace(a, 'word', 'xxx', a.count('word') - 1)
'cat word dog xxx mouse xxx'
+5
source

Source: https://habr.com/ru/post/1606139/


All Articles