re.sub参数之回调函数
from calendar import month_abbr
import re
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
if __name__ == '__main__':
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
# 先会执行匹配,然后将匹配到的match对象传入到回调函数中
print(datepat.sub(change_date, text))
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
if __name__ == '__main__':
re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!