【问题标题】:How to replace all occurences except the first one?如何替换除第一个之外的所有事件?
【发布时间】:2015-12-02 01:13:26
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x replace find-occurrences


    【解决方案1】:

    string.countrreplace 一起使用

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

    【讨论】:

    • 谢谢。但是,word 实际上是一组单词,我使用字典来替换它们,例如for i,j in dic.items(): line = rreplace(line,i,j,line.count(i)-1)。这不起作用
    • 请添加完整的代码,输入,输出。 don't work 到底是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2017-04-06
    • 2018-10-05
    • 2011-03-28
    • 2020-05-12
    • 1970-01-01
    相关资源
    最近更新 更多