How to replace all occurences except the first one?

后端 未结 1 446
半阙折子戏
半阙折子戏 2021-01-17 23:25

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\'         


        
相关标签:
1条回答
  • 2021-01-17 23:56

    Use a string.count together with the 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 讨论(0)
提交回复
热议问题