每天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