美文网首页
18.如何用Python来进行查询和替换一个文本字符串?

18.如何用Python来进行查询和替换一个文本字符串?

作者: vbuer | 来源:发表于2018-09-03 21:06 被阅读4次

可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])
replacement是被替换成的文本
string是需要被替换的文本
count是一个可选参数,指最大被替换的数量
例子:

import re
p = re.compile(’(blue|white|red)’)
print(p.sub(’colour’,'blue socks and red shoes’))
print(p.sub(’colour’,'blue socks and red shoes’, count=1))
输出:
colour socks and colour shoes
colour socks and red shoes

subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量
例如:

import re
p = re.compile(’(blue|white|red)’)
print(p.subn(’colour’,'blue socks and red shoes’))
print(p.subn(’colour’,'blue socks and red shoes’, count=1))
输出
(’colour socks and colour shoes’, 2)
(’colour socks and red shoes’, 1)

相关文章

网友评论

      本文标题:18.如何用Python来进行查询和替换一个文本字符串?

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