本节首先介绍如何使用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