python 正则表达式替换字符串中匹配的字符

import re  
street = '21 Ramkrishna Road'  
print(re.sub(r'Road$', 'Rd.', street))

利用re模块的sub函数,将结尾的Road用Rd.替换

一、前言
在字符串数据处理的过程中,正则表达式是我们经常使用到的,python中使用的则是re模块。下面会通过实际案例介绍 re.sub() 的详细用法,该函数主要用于替换字符串中的匹配项。

二、函数原型
首先从源代码来看一下该函数原型,包括各个参数及其意义:

def sub(pattern, repl, string, count=0, flags=0):
“””Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it’s passed the match object and must return
a replacement string to be used.”””
return _compile(pattern, flags).sub(repl, string, count)

从上面的代码中可以看到re.sub()方法中含有5个参数,下面进行一一说明(加粗的为必须参数):
(1)pattern:该参数表示正则中的模式字符串;
(2)repl:该参数表示要替换的字符串(即匹配到pattern后替换为repl),也可以是个函数;
(3)string:该参数表示要被处理(查找替换)的原始字符串;
(4)count:可选参数,表示是要替换的最大次数,而且必须是非负整数,该参数默认为0,即所有的匹配都会被替换;
(5)flags:可选参数,表示编译时用的匹配模式(如忽略大小写、多行模式等),数字形式,默认为0。