天天看點

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")