如何替换除第一个之外的所有出现? [英] How to replace all occurences except the first one?

查看:51
本文介绍了如何替换除第一个之外的所有出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

s='猫字狗字老鼠字's1='cat1 WORD dog1 WORD'

将被替换为

s='cat WORD dog REPLACED mouse REPLACED's1='cat1 WORD dog1 已替换'

我不能向后替换字符串,因为我不知道这个词在每一行出现了多少次.我确实想出了一个迂回的方法:

temp=s.replace('WORD','XXX',1)temp1=temp.replace('WORD','REPLACED')ss=temp1.replace('XXX','WORD')

但我想要一个更pythonic的方法.你有什么想法吗?

解决方案

使用 string.countrreplace

<预><代码>>>>def rreplace(s, old, new, 出现):... li = s.rsplit(旧,发生)...返回 new.join(li)...>>>一种'猫字狗字老鼠字'>>>rreplace(a, 'word', 'xxx', a.count('word') - 1)'猫字狗xxx老鼠xxx'

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'

will be replaced to

s='cat WORD dog REPLACED mouse REPLACED'
s1='cat1 WORD dog1 REPLACED'

I can't replace the string backward because I don't know how many time the word occurs on each line. I do figure out a circuitous way:

temp=s.replace('WORD','XXX',1)
temp1=temp.replace('WORD','REPLACED')
ss=temp1.replace('XXX','WORD')

But I want a more pythonic method. Do you have any idea?

解决方案

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'

这篇关于如何替换除第一个之外的所有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆