字符串正则匹配
re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
>>>import re
>>> re.findall(r'\bf[a-z]*','which foot or hand fell fastest')
['foot','fell','fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1','cat in the the hat')
'cat in the hat'
如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:
>>>'tea for too'.replace('too','two')
'tea for two'
数学
math模块为浮点运算提供了对底层C函数库的访问:
>>>import math
>>> math.cos(math.pi /4)
0.70710678118654757
>>> math.log(1024,2)
10.0
random提供了生成随机数的工具。
>>>import random
>>> random.choice(['apple','pear','banana'])
'apple'
>>> random.sample(range(100),10) # sampling without replacement
[30,83,16,4,8,81,41,50,18,33]
>>> random.random() # random float
0.17970987693706186
>>> random.randrange(6) # random integer chosen from range(6)
4