[Python迷惑性爲] 利用replace方法實現從右到左替換字符串

replace方法原型

str.replace(old, new[, max])

  •  old  -- 將被替換的子字符串。
  • new -- 新字符串,用於替換old子字符串。
  • max -- 可選次數, 替換不超過 max 次

由於字符串類型自帶的replace方法默認且只允許實現從左向右檢索,當出現需要從右向左檢索的時候可以使用以下方法實現:

通過全部取反再取反的方法實現(original)

def right_replace(string, old, new, max=1):
    return string[::-1].replace(old[::-1], new[::-1], max)[::-1]

計數方法

引自http://blog.csdn.net/c465869935/article/details/71106967

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

測試用例

right_replace('[1234::8012:80.1.1.1]:80',':80','')
right_replace('eeeeee', 'e', 'E', 3)
right_replace('eeeeee', 'e', 'E', 2)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章