利用replace方法实现从右到左替换字符串

2020-01-14  本文已影响0人  日落_3d9f

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]
上一篇 下一篇

猜你喜欢

热点阅读