温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Python实现的从右到左字符串替换

发布时间:2021-04-13 09:38:09 来源:亿速云 阅读:346 作者:小新 栏目:开发技术

小编给大家分享一下如何使用Python实现的从右到左字符串替换,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一 . 前言

需要用到,但是发现python没有从右边开始替换的内置方法,默认的replace只是从左边开始,就索性自己写个,有需求的自己可以在此基础上搞个python hack,给str增加个rreplace方法。

二. 实现

利用python 的其它内置方法,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

学无止境,最后搜索发现有种核心代码只有1行的实现方法

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 基本一致

参数:

self --  源字符串。
old  --  将被替换的子字符串。
new  --  新字符串,用于替换old子字符串。
max  --  可选字符串, 替换不超过 max 次

返回:

被替换后的字符串

举几个用例比较下就清楚了:

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

运行结果:

l3mon tr33
lemon tre3
lemon tr33
lemon
lemon tree

以上是“如何使用Python实现的从右到左字符串替换”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI