码迷,mamicode.com
首页 > 编程语言 > 详细

【python cookbook】【字符串与文本】6.以不区分大小写的方式对文本做查找和替换

时间:2016-08-20 17:55:24      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

问题:以不区分大小写的方式对文本做查找和替换

解决方法:使用re模块,并对各种操作都添加上re.IGNORECASE标记

text=UPPER PYTHON,lower python,Mixed Python

print (re.findall(python,text,re.IGNORECASE))
print (re.sub(python,snake,text,flags=re.IGNORECASE))
>>> ================================ RESTART ================================
>>> 
[PYTHON, python, Python]
UPPER snake,lower snake,Mixed snake
>>> 

以上待替换的文本与匹配的文本大小写并不吻合,例如Python替换为snake,而非Snake。若要修正该问题,需使用一个支撑函数:

import re

text=UPPER PYTHON,lower python,Mixed Python

def matchcase(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()
        #capitalize()将字符串的第一个字母变成大写,其他字母变小写。
        else:
            return word
    return replace

print (re.sub(python,matchcase(snake),text,flags=re.IGNORECASE))
>>> ================================ RESTART ================================
>>> 
UPPER SNAKE,lower snake,Mixed Snake
>>> 

 

【python cookbook】【字符串与文本】6.以不区分大小写的方式对文本做查找和替换

标签:

原文地址:http://www.cnblogs.com/apple2016/p/5790812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!