Ook*_*ker 7 python replace python-3.x find-occurrences
如何替换除字符串中第一个以外的所有重复单词?那就是这些字符串
s='cat WORD dog WORD mouse WORD'
s1='cat1 WORD dog1 WORD'
Run Code Online (Sandbox Code Playgroud)
将被替换为
s='cat WORD dog REPLACED mouse REPLACED'
s1='cat1 WORD dog1 REPLACED'
Run Code Online (Sandbox Code Playgroud)
我无法向后替换字符串,因为我不知道每行出现的字数.我确实想出了一个迂回的方式:
temp=s.replace('WORD','XXX',1)
temp1=temp.replace('WORD','REPLACED')
ss=temp1.replace('XXX','WORD')
Run Code Online (Sandbox Code Playgroud)
但我想要一个更加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'
Run Code Online (Sandbox Code Playgroud)