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\'
Use a string.count together with the rreplace
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'