您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用Python實(shí)現(xiàn)的從右到左字符串替換,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
需要用到,但是發(fā)現(xiàn)python沒有從右邊開始替換的內(nèi)置方法,默認(rèn)的replace
只是從左邊開始,就索性自己寫個(gè),有需求的自己可以在此基礎(chǔ)上搞個(gè)python hack,給str增加個(gè)rreplace方法。
利用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
學(xué)無止境,最后搜索發(fā)現(xiàn)有種核心代碼只有1行的實(shí)現(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 次
返回:
被替換后的字符串
舉幾個(gè)用例比較下就清楚了:
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")
運(yùn)行結(jié)果:
l3mon tr33
lemon tre3
lemon tr33
lemon
lemon tree
以上是“如何使用Python實(shí)現(xiàn)的從右到左字符串替換”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。