python正则(3)使用sub进行替换

本节首先介绍如何使用sub

我们经常遇到写作文的时候要把小明改成小红这样的二次创造,在word里面你就ctrl+f找到解决了,那么如何使用正则表达式解决呢?

sub的参数介绍

re.sub(pattern,repl,string,max)
translation as below:
re.sub(你准备替换谁,替换成什么,在哪里替换,最多替换几次)

给段代码你就明白了【默认替换无穷次】

import re
str = “umji is the best umji in the world although GFRIEND is so lovely”
pattern = r"umji"
newstr = re.sub(pattern,“sowon”,str)
print(newstr)

运行结果是

sowon is the best sowon in the world although GFRIEND is so lovely

如果改成最多替换一次

import re
str = “umji is the best umji in the world although GFRIEND is so lovely”
pattern = r"umji"
newstr = re.sub(pattern,“sowon”,str,1)
print(newstr)

运行结果就会变成

sowon is the best umji in the world although GFRIEND is so lovely

猜你喜欢

转载自blog.csdn.net/weixin_43914889/article/details/87979016
今日推荐