1. text = 'UPPER PYTHON, lower python, Mixed Python'
    2. def matchcase(word):
    3. def replace(m):
    4. text = m.group()
    5. if text.isupper():
    6. return word.upper()
    7. elif text.islower():
    8. return word.lower()
    9. elif text[0].isupper():
    10. return word.capitalize()
    11. else:
    12. return word
    13. return replace
    14. print(re.sub('python', matchcase('snake'), text, flags=re.I))
    15. >>> UPPER SNAKE, lower snake, Mixed Snake