Guest User

Untitled

a guest
Jan 22nd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. # re.sub 在替换时可以接受一个回调函数
  2.  
  3. def matchcase(word):
  4. '''暂时只能处理全大写、全小写、首字母大写的情况'''
  5. def replace(m):
  6. '''m 是正则 catch 到的 group object'''
  7. text = m.group()
  8. if text.isupper():
  9. return word.upper()
  10. elif text.islower():
  11. return word.lower()
  12. elif text[0].isupper():
  13. return word.capitalize()
  14. else:
  15. return word
  16. return replace
  17.  
  18. # 用法:
  19. # 第二个参数是一个回调函数(matchcase 运行后返回的就是一个函数)
  20. re.sub('python', matchcase('snake'), 'Python', flags=re.IGNORECASE) # 返回 Snake
  21. re.sub('python', matchcase('snake'), 'PYTHON', flags=re.IGNORECASE) # 返回 SNAKE
Add Comment
Please, Sign In to add comment