失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python忽略大小写_Python字符串忽略大小写实现搜索和替换

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

时间:2018-08-27 21:14:46

相关推荐

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

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

# _*_coding:utf-8_*_

# Time : 18/8/13 下午9:36

# Author : nock.chen

# Site :

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 :

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匹配可能还不够。

本文由 空心菜 创作,采用 知识共享署名4.0 国际许可协议进行许可

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名

最后编辑时间为: Aug 14, at 02:10 pm

如果觉得《python忽略大小写_Python字符串忽略大小写实现搜索和替换》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。