Python实现字符串的两种方法。
方法一:使用python字符串的内置方法replace方法实现替换
def strreplace(msg,key,value):
msg.replace(key,value)
return msg
方法二:使用正则表达式sub()方法实现python的字符串的替换
re.sub共有五个参数。
re.sub(pattern, repl, string, count=0, flags=0)
其中三个必选参数:pattern, repl, string
两个可选参数:count, flags
pattern,表示正则中的模式字符串,这个没太多要解释的。
repl,就是replacement,被替换,的字符串的意思。
string,即表示要被处理,要被替换的那个string字符串。
import re
def strreplace2(msg,key,value):
事先用正则的方法,把他给编译好
m=re.compile(key)
ret=m.sub(value,msg)
return ret
网友评论