import re if __name__ == '__main__': text = "UPPER PYTHON, lower python, mixed Python" # 想要找到所有的python,可以在函数里面找一下有没有flag关键字,并设为re.IGNORECASE pythons = re.findall('python', text, flags=re.IGNORECASE) print(pythons) # 但是这样在替换的时候就有问题发生,不能把替换文本的大小写设置成和原文本一样 python_replace = re.sub('python', 'snake', text, flags=re.IGNORECASE) print(python_replace) # 这个时候我们需要一个辅助函数 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() else: return word return replace python_replace_with_func = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) print(python_replace_with_func) # 这个辅助函数结构陌生,这里记个笔记备注一下防止以后再看忘记: # 1.首先,sub函数检测到要调用matchcase函数,进入函数体返回replace函数 sub->matchcsae # 2.此时matchcase函数的输入word仍在堆栈中等待调用 matchcase -replace-> sub # 3.在替换的时候,sub函数将识别到的python替换成replace(被识别到的部分) text -> (a1,a2,a3,...) # 4.replace函数返回大小写处理结果 replace(a1), replace(a2), ... # 5.函数返回被替换字符串,re.sub函数进行替换 将识别到的关键词替换成处理过的word