生命价值不在于获取多少,生命价值在于付出多少。有钱的人更有钱,这往往是一种必然。
本文实例讲述了Python实现的从右到左字符串替换方法。分享给大家供大家参考,具体如下:
一 . 前言
需要用到,但是发现python没有从右边开始替换的内置方法,默认的replace只是从左边开始,就索性自己写个,有需求的自己可以在此基础上搞个python hack,给str增加个rreplace方法。
二. 实现
利用python 的其它内置方法,11行代码就可以了
def rreplace(self, old, new, *max):
count = len(self)
if max and str(max[0]).isdigit():
count = max[0]
while count:
index = self.rfind(old)
if index >= 0:
chunk = self.rpartition(old)
self = chunk[0] + new + chunk[2]
count -= 1
return self
学无止境,最后搜索发现有种核心代码只有1行的实现方法
def rreplace(self, old, new, *max):
count = len(self)
if max and str(max[0]).isdigit():
count = max[0]
return new.join(self.rsplit(old, count))
三. 用法
和 replace 基本一致
参数:
self -- 源字符串。
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
返回:
被替换后的字符串
举几个用例比较下就清楚了:
print rreplace("lemon tree", "e", "3")
print rreplace("lemon tree", "e", "3", 1)
print rreplace("lemon tree", "e", "3", 2)
print rreplace("lemon tree", "tree", "")
print rreplace("lemon tree", "notree", "notmatch")
运行结果:
l3mon tr33
lemon tre3
lemon tr33
lemon
lemon tree
希望本文所述对大家Python程序设计有所帮助。
到此这篇关于Python实现的从右到左字符串替换方法示例就介绍到这了。人只有将寂寞坐断,才可以重拾喧闹;把悲伤过尽,才可以重见欢颜;把苦涩尝遍,就会自然回甘。信了这些,就可以更坦然地面对人生沟壑,走过四季风霜。言者随意,但生命毕竟是一个漫长的过程,每一寸时光都要自己亲历,每一杯雨露都要自己亲尝。更多相关Python实现的从右到左字符串替换方法示例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!