How to replace all occurences except the first one?
Asked Answered
D

1

8

How to replace all the repeated words except the first one in the string? That is these strings

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

will be replaced to

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

I can't replace the string backward because I don't know how many time the word occurs on each line. I do figure out a circuitous way:

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

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

Dichromate answered 6/9, 2015 at 10:16 Comment(0)
S
10

Use a string.count together with the rreplace

>>> 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'
Schlemiel answered 6/9, 2015 at 10:25 Comment(2)
thanks for that. However, word is actually a set of words, and I use a dictionary to replace them, e.g. for i,j in dic.items(): line = rreplace(line,i,j,line.count(i)-1). This doesn't workDichromate
Please add the complete code, input, output. And what exactly don't work?Schlemiel

© 2022 - 2024 — McMap. All rights reserved.