且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何替换除第一个之外的所有出现?

更新时间:2023-02-19 22:19:38

使用 string.countrreplace

>>>def rreplace(s, old, new, 出现):... li = s.rsplit(旧,发生)...返回 new.join(li)...>>>一种'猫字狗字老鼠字'>>>rreplace(a, 'word', 'xxx', a.count('word') - 1)'猫字狗xxx老鼠xxx'

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?

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'