如何替换除第一个以外的所有出现的事件?

时间:2015-09-06 10:16:45

标签: python python-3.x replace find-occurrences

如何替换除字符串中第一个以外的所有重复单词?那就是这些字符串

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

将被替换为

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

我不能replace the string backward,因为我不知道每行发生这个词的次数。我确实想出了一个迂回的方式:

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

但我想要一个更加pythonic的方法。你有什么想法吗?

1 个答案:

答案 0 :(得分:7)

string.countrreplace

一起使用
>>> 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'
相关问题