python字符串替换re.sub()方法解析
作者:郭雪原 时间:2022-02-14 16:51:42
pattern可以是一个字符串也可以是一个正则,用于匹配要替换的字符,如果不写,字符串不做修改。\1 代表第一个分组
repl是将会被替换的值,repl可以是字符串也可以是一个方法。如果是一个字符串,反斜杠会被处理为逃逸字符,如\n会被替换为换行,等等。repl如果是一个function,每一个被匹配到的字段串执行替换函数。
\g<1> 代表前面pattern里面第一个分组,可以简写为\1,\g<0>代表前面pattern匹配到的所有字符串。
count是pattern被替换的最大次数,默认是0会替换所有。有时候可能只想替换一部分,可以用到count
实例1:
a = re.sub(r'hello', 'i love the', 'hello world')
print(a)<br data-filtered="filtered">'i love the world' #hello world里面的hello被 i love the替换
实例2:
>>> a = re.sub(r'(\d+)', 'hello', 'my numer is 400 and door num is 200')
>>> a
'my numer is hello and door num is hello' #数字400 和 200 被hello替换
实例3:
a = re.sub(r'hello (\w+), nihao \1', r'emma','hello sherry, nihao sherry')
>>> a
'emma' #\1代表第一个分组的值即sherry,因为有两个sherry,所以用\1可以指代第二个,这样整个字符串被emma替换
示例4:
>>> a = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2-\3-\1', '2018-06-07')
>>> a
'06-07-2018'
>>> a = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\g<2>-\g<3>-\g<1>', '2018-06-07')
>>> a
'06-07-2018' #\2 和 \g<2> 指代的的都是前面的第二个分组
示例5:
import re
def replace_num(str):
numDict = {'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
print(str.group())
return numDict[str.group()]
my_str = '2018年6月7号'
a = re.sub(r'(\d)', replace_num, my_str)
print(a) #每次匹配一个数字,执行函数,获取替换后的值
和sub()函数一样,只是返回的是一个tuple,替换后的字符串和替换的个数
来源:https://www.cnblogs.com/guoxueyuan/p/9151678.html
标签:python,字符串,替换,re.sub()
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
javabean servlet jsp实现分页功能代码解析
2023-06-13 15:21:24
![](https://img.aspxhome.com/file/2023/2/63032_0s.png)
基于python3 pyQt5 QtDesignner实现窗口化猜数字游戏功能
2022-02-05 00:56:54
![](https://img.aspxhome.com/file/2023/6/81616_0s.png)
django自定义模板标签过程解析
2023-07-29 12:34:57
![](https://img.aspxhome.com/file/2023/3/70713_0s.png)
PHP入门基础之注释的写法
2023-10-20 07:26:17
nlp计数法应用于PTB数据集示例详解
2023-10-26 17:24:07
Python对列表中的各项进行关联详解
2023-10-26 20:19:34
![](https://img.aspxhome.com/file/2023/0/97250_0s.png)
Python+selenium 获取一组元素属性值的实例
2021-06-06 02:28:27
HTML5中 b 和 i 标签将语义化
2008-03-16 13:43:00
基于Python制作打地鼠小游戏
2022-04-07 09:13:34
从np.random.normal()到正态分布的拟合操作
2023-09-09 18:00:01
![](https://img.aspxhome.com/file/2023/4/103144_0s.jpg)
python实现串口通信的示例代码
2023-08-04 03:44:24
![](https://img.aspxhome.com/file/2023/7/61737_0s.jpg)
MYSQL教程:如何选择正确的数据列类型
2009-02-27 16:05:00
几个好用的Asp自定义函数
2007-09-26 14:28:00
python 格式化输出百分号的方法
2023-07-17 08:23:27
Dreamweaver量身打造Wordpress留言板(二)
2009-12-12 17:35:00
![](https://img.aspxhome.com/file/UploadPic/200912/12/1556470-95s.gif)
ASP四级连动下拉列表程序段
2009-07-03 15:33:00
(小技巧)复制消息对话框的内容
2008-10-21 10:51:00
Python内建类型int源码学习
2023-07-02 19:22:15
![](https://img.aspxhome.com/file/2023/0/59150_0s.png)
HTML的基本元素
2010-03-16 12:39:00
图片垂直居中的使用技巧
2008-05-28 12:45:00