Python字符串忽略大小写实现搜索和替换

in 互联网技术 with 0 comment  访问: 4,446 次

为了针对字符串操作忽略大小写,我们可以使用re模块的时候利用re.IGNORECASE标记参数来达到效果,示例如下:

#!/usr/bin/env python3
# _*_coding:utf-8_*_
# Time    : 18/8/13 下午9:36
# Author  : nock.chen
# Site    : https://fashengba.com

import re
string_info = "Life is too short. I use PYTHON, I Love python, Python is Good"

capital_python = re.findall('python', string_info, flags=re.IGNORECASE)
sub_result = re.sub('python', 'snake', string_info, flags=re.IGNORECASE)

print('find result is: %s, sub result is: %s' % (capital_python, sub_result))

Result:

find result is: ['PYTHON', 'python', 'Python'], sub result is: Life is too short. I use snake, I Love snake, snake is Good

如上的示例,在用re.sub方法做替换的时候有一个小缺陷,替换字符串并不会自动跟你要匹配替换掉的字符串大小写保持一致,如果你需要做到保持一致,需要增加一个辅助函数来做这个事情,示例如下:

#!/usr/bin/env python3
# _*_coding:utf-8_*_
# Time    : 18/8/13 下午9:36
# Author  : nock.chen
# Site    : https://fashengba.com
import re
string_info = "Life is too short. I use PYTHON, I Love python, Python is Good"


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 replace

sub_result = re.sub('python', match_case('snake'), string_info, flags=re.IGNORECASE)
print(sub_result)

Result:

Life is too short. I use SNAKE, I Love snake, Snake is Good

matchcase('snake')返回了一个回调函数(参数必须是一个match对象),sub()函数除了可以接受替换字符串以外,还可以接受一个回调函数。

对于一般的忽略大小写的匹配操作,简单的传递一个re.IGNORECASE标志参数就已经足够了。 但是需要注意的是,这个对于某些需要大小写转换的Unicode匹配可能还不够。

WeZan