天天看点

python 从右到左字符串替换方法实现

一 . 前言

需要用到,但是发现python没有从右边开始替换的内置方法,默认的replace只是从左边开始,就索性自己写个,有需求的自己可以在此基础上搞个python hack,给str增加个rreplace方法。

转载、引用请尊重原作者,注明作者与来源链接: http://blog.csdn.net/c465869935/article/details/71106967。

二. 实现

利用python 的其它内置方法,11行代码就可以了

def rreplace(self, old, new, *max):
    count = len(self)
    if max and str(max[]).isdigit():
        count = max[]
    while count:
        index = self.rfind(old)
        if index >= :
            chunk = self.rpartition(old)
            self = chunk[] + new + chunk[]
        count -= 
    return self
           

学无止境,最后搜索发现有种核心代码只有1行的实现方法

def rreplace(self, old, new, *max):
    count = len(self)
    if max and str(max[]).isdigit():
        count = max[]
    return new.join(self.rsplit(old, count))
           

三. 用法

和 replace 基本一致

参数:

self --  源字符串。
old  --  将被替换的子字符串。
new  --  新字符串,用于替换old子字符串。
max  --  可选字符串, 替换不超过 max 次
           

返回:

被替换后的字符串
           

举几个用例比较下就清楚了:

rreplace("lemon tree", "e", "3")
rreplace("lemon tree", "e", "3", )
rreplace("lemon tree", "e", "3", )
rreplace("lemon tree", "tree", "")
rreplace("lemon tree", "notree", "notmatch")