python - 如何替换除第一个以外的所有事件?

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

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

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

最佳答案

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'

关于python - 如何替换除第一个以外的所有事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422431/

相关文章:

python - django.template.exceptions.TemplateSyntaxError : Could not parse some characters: |{{b.count}}||rangef

python - 为什么 Python 会默默地转换为 0.0?

django - 在 Django 中查找特定范围内的重叠日期

python - 从 next_sibling 获取文本 - BeautifulSoup 4

python - 在 Python 中替换字符串中的字符

mysql - 查询从列内容中删除多个字符

python - 如何将本地编译的 OpenCV 添加到 Python 路径?

python - 将多个文件合并到一个数据框中

python - 易于使用的 Python 加密库/包装器?

Javascript 替换未按预期工作