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()
        else:
            return word
    return replace # 返回内部函数名

text = 'UPPER PYTHON, lower python, Mixed Python'
import re
dd=re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
print(dd)

打印结果:
UPPER SNAKE, lower snake, Mixed Snake
装饰器知识:Python装饰器的通俗理解

你可能感兴趣的:(python,python基础语法)