美文网首页
Python字符串替换的两种实现方法

Python字符串替换的两种实现方法

作者: 暖遇 | 来源:发表于2018-09-11 16:18 被阅读0次

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

相关文章

网友评论

      本文标题:Python字符串替换的两种实现方法

      本文链接:https://www.haomeiwen.com/subject/uvmugftx.html