前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中的re模块

python中的re模块

作者头像
Tim在路上
发布2020-08-04 22:20:28
5870
发布2020-08-04 22:20:28
举报

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

可以使用re模块中的sub()函数或者subn()函数来进行查询和替换, 格式: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’))
colour socks and colourshoes
>>>print(p.sub(‘colour’,'blue socks and red shoes’,count=1))
colour socks and redshoes
print(p.subn('colour','blue socks and red shoes'))
('colour socks and colour shoes', 2)
print(p.subn('colour','blue socks and red shoes',count=1))
('colour socks and red shoes', 1)

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

Python里面match()和search()的区别?

re模块中match(pattern,string[,flags]),检查string的==开头==是否与pattern匹配,这个是全匹配,但是只要是在开头匹配就行。 re模块中re.search(pattern,string[,flags]),在string搜索pattern的第一个匹配值,而且是对当前的字符串的全匹配。

<_sre.SRE_Match object; span=(0, 5), match='super'>
>>>print(re.match(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.match(‘super’, ‘insuperable’))
None
>>>print(re.search(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.search(‘super’, ‘insuperable’).span())
(2, 7)
print(re.search('super','msuperstition'))
<_sre.SRE_Match object; span=(1, 6), match='super'>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 如何用Python来进行查询和替换一个文本字符串?
  • Python里面match()和search()的区别?
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档