Python實現(xiàn)的從右到左字符串替換方法示例
本文實例講述了Python實現(xiàn)的從右到左字符串替換方法。分享給大家供大家參考,具體如下:
一 . 前言
需要用到,但是發(fā)現(xiàn)python沒有從右邊開始替換的內(nèi)置方法,默認的replace
只是從左邊開始,就索性自己寫個,有需求的自己可以在此基礎上搞個python hack,給str增加個rreplace方法。
二. 實現(xiàn)
利用python 的其它內(nèi)置方法,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
學無止境,最后搜索發(fā)現(xiàn)有種核心代碼只有1行的實現(xiàn)方法
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
基本一致
參數(shù):
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相關內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python3連接MySQL數(shù)據(jù)庫實例詳解
這篇文章主要為大家詳細介紹了python3連接MySQL數(shù)據(jù)庫實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05python中使用enumerate函數(shù)遍歷元素實例
這篇文章主要介紹了python中使用enumerate函數(shù)遍歷元素實例,這是一個比較簡單的例子,需要的朋友可以參考下2014-06-06