Python实现查找匹配项作处理后再替换回去的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现查找匹配项作处理后再替换回去的方法。分享给大家供大家参考,具体如下:

这里实现Python在对找到的匹配项进行适当处理后,再替换掉原来那个匹配的项。

#!/usr/bin/python
# coding=GBK
import re
# 对m作适当处理后返回结果
def fun(m):
  print("in: %s" %m.group(0))
  ret = m.group(0).upper()[::-1]
  return ret
src = "what [can] I do for can you[can] come on"
pat = "(?<=
)(can)(?=
)"
#print(re.search(pat, src).group(1))
#result = re.sub(pat,lambda m:m.group(1).upper()[::-1], src)
# 使用lambda
result1 = re.sub(pat, lambda m:m.group(0).upper()[::-1], src)
print("result1: %s\n" %result1)
# 在re.sub中使用函数
result2 = re.sub(pat, fun, src)
print("result2: %s" %result2)

运行输出:

[zcm@python #112]$./del.py
result1: what [NAC] I do for can you[NAC] come on
in: can
in: can
result2: what [NAC] I do for can you[NAC] come on
[zcm@python #113]$

看到了吗,所有匹配"[can]"的项都被“转换成大写并逆顺”了

更多关于Python相关内容可查看本站专题:《Python字符串操作技巧汇总》、《Python常用遍历技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程

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

相关文章

selenium+python自动化测试之使用webdriver操作浏览器的方法

WebDriver简介 selenium从2.0开始集成了webdriver的API,提供了更简单,更简洁的编程接口。selenium webdriver的目标是提供一个设计良好的面向对...

python+rsync精确同步指定格式文件

本文实例为大家分享了python+rsync精确同步指定格式文件的具体代码,供大家参考,具体内容如下 # coding: utf-8 #!/usr/bin/env python '...

Python实现数值积分方式

Python实现数值积分方式

原理: 利用复化梯形公式,复化Simpson公式,计算积分。 步骤: import math """测试函数""" def f(x,i): if i == 1: re...

用Python输出一个杨辉三角的例子

关于杨辉三角是什么东西,右转维基百科:杨辉三角 稍微看一下直观一点的图:复制代码 代码如下:        1       1 1      1 2 1     1 3 3 1    1...

用python中的matplotlib绘制方程图像代码

用python中的matplotlib绘制方程图像代码

import numpy as np import matplotlib.pyplot as plt def main(): # 设置x和y的坐标范围 x=np.aran...