10.5. 字符串模式匹配

re 模块为高级字符串处理提供正则表达式工具。对于复杂的匹配和操作,正则表达式提供简洁,优化的解决方案:

  1. >>> import re
  2. >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
  3. ['foot', 'fell', 'fastest']
  4. >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
  5. 'cat in the hat'

当只需要简单的功能时,首选字符串方法因为它们更容易阅读和调试:

  1. >>> 'tea for too'.replace('too', 'two')
  2. 'tea for two'