2015-09-06 81 views
4

如何替换字符串中除第一个之外的所有重复单词?也就是说这些字符串如何替换除第一个之外的所有事件?

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的方法。你有什么主意吗?

回答

5

使用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' 
+0

感谢与一个string.count在一起。然而,“单词”实际上是一组单词,我用一个字典来替换它们,例如'对于i,j in dic.items():line = rreplace(line,i,j,line.count(i)-1)'。这不起作用 – Ooker

+0

请添加完整的代码,输入,输出。什么“不工作”? – luoluo

相关问题