溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Python實(shí)現(xiàn)的從右到左字符串替換

發(fā)布時(shí)間:2021-04-13 09:38:09 來源:億速云 閱讀:355 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下如何使用Python實(shí)現(xiàn)的從右到左字符串替換,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

一 . 前言

需要用到,但是發(fā)現(xiàn)python沒有從右邊開始替換的內(nèi)置方法,默認(rèn)的replace只是從左邊開始,就索性自己寫個(gè),有需求的自己可以在此基礎(chǔ)上搞個(gè)python hack,給str增加個(gè)rreplace方法。

二. 實(shí)現(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

學(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è)資訊頻道!

向AI問一下細(xì)節(jié)

免責(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)容。

AI