如何替换字符串中除第一个以外的所有重复词?也就是这些字符串
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 的方法。你有什么想法吗?
最佳答案
将 string.count
与 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'
关于python - 如何替换除第一个以外的所有事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422431/