打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python查找替换的简单技巧
  • 最简单的查找和替换
    在Python中查找和替换非常简单,如果当前对象是一个字符串str时,你可以使用该类型提供的find()或者index()方法查找指定的字符,如果能找到则会返回字符第一次出现的索引,如果不存在则返回-1。

example:

s = 'Cat and Dog'print(s.find('Dog'),end = ' ')print(s.index('Dog'),end = ' ')print(s.find('duck'),end = ' ')# 输出# 8 8 -1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果要替换字符串,使用replace()方法就好了。

s = 'Cat and Dog'print(s.replace('cat','Dog'))# 'Dog and Dog'
  • 1
  • 2
  • 3
  • 4
  • 通配符查找匹配
    如果你觉得上面的功能还不能满足你,你想使用通配符来查找字符串?没问题!fnmatch这个库就能满足你的要求,看例子!
import fnmatchs = 'fish and mouse'fnmatch.fnmatch(s,'fish*')fnmatch.fnmatch(s,'fish*m?')fnmatch.fnmatch(s,'f*and*m*')# True False True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 正则表达式查找替换
    如果你需要查找比较复杂的字符规则,正则表达式是你不二的选择。下面是正则查找的简单示例。
import res = 'let us go shopping on 2018/5/12'pattern = r'\d+'re.findall(pattern,s)#['2018','5','12']re.search(pattern,s).group()#'2018'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

接下来你可能需要用正则表达式去替换某些字符,那么你需要了解re.sub()方法,看例子。

s = 'I want {size}m space.'re.sub(r'\{size\}','100',s)//'I want 100m space.'s = 'let us go shopping on 2018/5/12're.sub('(\d+)/(\d+)/(\d+)', r'\3-\1-\2', s)#'let us go shopping on 2018-5-12'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

re.sub()远比你相像的强大的多。在上面的例子里你可以替换类似于{color}这样的模板字符,也可以把正则匹配到的所有分组调换顺序,例如第二个例子一共匹配了3个分组,然后把第3个分组放到最前面 r’\3-\1-\2’,看明白了吗?

s = 'gcy is talking to kk.'name1 = 'Tom'name2 = 'Jerry'pattern = r'(.*)({0})(.*)({1})(.*)'.format(name1, name2)print re.sub(pattern, r'\1\4\3\2\5', s)# kk is talking to gcy.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

其实你还可以自定义替换函数,也就是re.sub()的第二个参数。

def change_date(m): from calendar import month_abbr mon_name = month_abbr[int(m.group(1))] return '{} {} {}'.format(m.group(2), mon_name, m.group(3))s = 'let us go shopping on 2018/5/12'pattern = r'(\d+)/(\d+)/(\d+)'print re.sub(pattern, change_date, s)# let us go shopping on 12 may 2018
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

最后给与完整版的例子:

def match_case(word):    def replace(m):        text = m.group()        if text.isupper():            return word.upper()        elif text.islower():            return word.lower()        elif text[0].isupper():            return word.capitalize()        else:            return word    return replaces = 'LOVE PYTHON, love python, Love Python'print re.sub('python', match_case('money'), s, flags=re.IGNORECASE)# LOVE MONEY, love money, Love Money
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

其实正则表达式还有很多玩法,如果你想让正则和通配符混合着用,一点问题都没有,因为fnmatch还有一个translate()的方法,可以让你把通配符无痛转换成正则表达式,你爱怎么玩就怎么玩。

fnmatch.translate('C*and*D*')#'C.*and.*D.*'
  • 1
  • 2
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【Python爬虫学习笔记(2)】正则表达式(re模块)相关知识点总结
Python正则表达式由浅入深(四)
python的正则表达式re模块的常用方法
Python中re(正则表达式)模块详解
Python正则表达式快速学习
正确的正则表达式学习方法是放弃抵抗^_^
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服