以上例子有一定的局限性,待替换文本与匹配的文本大小写并不吻合。
因此,我们需要一个辅助函数。
In [21]: 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 ...: In [23]: re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) Out[23]: 'UPPER SNAKE, lower snake, Mixed Snake'个人理解: text = m.group()中 m.group()即为使用 ‘python’在 原文本中 匹配到的内容。