美文网首页
利用replace方法实现从右到左替换字符串

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

作者: 日落_3d9f | 来源:发表于2020-01-14 16:04 被阅读0次

    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]
    

    相关文章

      网友评论

          本文标题:利用replace方法实现从右到左替换字符串

          本文链接:https://www.haomeiwen.com/subject/zwdaactx.html