Python实现的从右到左字符串替换方法示例

yipeiwu_com5年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python实现2014火车票查询代码分享

代码基于Python3.3.3,PyQt5.1.1 复制代码 代码如下:# -*- coding: utf-8 -*-# Python 3.3.3# PyQt 5.1.1import s...

Python Web框架Flask下网站开发入门实例

Python Web框架Flask下网站开发入门实例

一、Flask简介 Flask 是一个 Python 实现的 Web 开发微框架。官网:http://flask.pocoo.org/ 二、Demo 1、代码结构 复制代码 代码如下:...

总结用Pdb库调试Python的方式及常用的命令

用Pdb调试有多种方式 使用 Pdb调试 Python的程序的方式主要是下面的三种!下面逐一介绍 命令行加-m参数 命令行启动目标程序,加上-m参数,这样调用 testPdb.py的...

Python计算时间间隔(精确到微妙)的代码实例

Python计算时间间隔(精确到微妙)的代码实例

使用python中的datetime import datetime oldtime=datetime.datetime.now() print oldtime; x=1 while...

Python Web框架之Django框架文件上传功能详解

Python Web框架之Django框架文件上传功能详解

本文实例讲述了Python Web框架之Django框架文件上传功能。分享给大家供大家参考,具体如下: 上传方式: - Form表单上传文件 - Ajax上传文件 - 基于form表单和...