每天CookBook之Python-026

  • 在re.sub中使用函数
import re

text = 'UPPER PYTHON, lower python, Mixed 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


print(re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE))
UPPER PYTHON, lower python, Mixed Python
UPPER SNAKE, lower snake, Mixed Snake
posted @ 2016-07-13 21:28  4Thing  阅读(89)  评论(0编辑  收藏  举报