Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # re.sub 在替换时可以接受一个回调函数
- def matchcase(word):
- '''暂时只能处理全大写、全小写、首字母大写的情况'''
- def replace(m):
- '''m 是正则 catch 到的 group object'''
- 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
- # 用法:
- # 第二个参数是一个回调函数(matchcase 运行后返回的就是一个函数)
- re.sub('python', matchcase('snake'), 'Python', flags=re.IGNORECASE) # 返回 Snake
- re.sub('python', matchcase('snake'), 'PYTHON', flags=re.IGNORECASE) # 返回 SNAKE
Add Comment
Please, Sign In to add comment