Python实现的从右到左字符串替换方法示例
本篇章节讲解Python实现的从右到左字符串替换方法。分享给大家供大家参考,具体如下: 一 . 前言需要用到,但是发现python没有从右边开始替换的内置方法,默认的 二. 实现利用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,*max): count = len(self) if max and str(max[0]).isdigit(): count = max[0] return new.join(self.rsplit(old,count)) 三. 用法和 参数:
返回:
举几个用例比较下就清楚了: print rreplace("lemon tree","e","3") print rreplace("lemon tree","3",1) print rreplace("lemon tree",2) print rreplace("lemon tree","tree","") print rreplace("lemon tree","notree","notmatch") 运行结果:
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》 希望本文所述对大家Python程序设计有所帮助。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |