rreplace - 如何替换字符串中最后一次出现的表达式? [英] rreplace - How to replace the last occurrence of an expression in a string?

查看:49
本文介绍了rreplace - 如何替换字符串中最后一次出现的表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中是否有一种快速替换字符串的方法,但不是像 replace 那样从头开始,而是从末尾开始?例如:

<预><代码>>>>def rreplace(旧的,新的,发生的)>>>... # 用新替换旧的最后一次出现的代码>>>'<div><div>你好</div></div>'.rreplace('</div>','</bad>',1)>>>'<div><div>你好</div></bad>'

解决方案

>>>def rreplace(s, old, new, 出现):... li = s.rsplit(旧,发生)...返回 new.join(li)...>>>秒'1232425'>>>rreplace(s, '2', ' ', 2)'123 4 5'>>>rreplace(s, '2', ' ', 3)'1 3 4 5'>>>rreplace(s, '2', ' ', 4)'1 3 4 5'>>>rreplace(s, '2', ' ', 0)'1232425'

Is there a quick way in Python to replace strings but, instead of starting from the beginning as replace does, starting from the end? For example:

>>> def rreplace(old, new, occurrence)
>>>     ... # Code to replace the last occurrences of old by new

>>> '<div><div>Hello</div></div>'.rreplace('</div>','</bad>',1)
>>> '<div><div>Hello</div></bad>'

解决方案

>>> def rreplace(s, old, new, occurrence):
...  li = s.rsplit(old, occurrence)
...  return new.join(li)
... 
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'

这篇关于rreplace - 如何替换字符串中最后一次出现的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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