Python标准库概览

总结

这个部分讲了一些常用的python库的方法。一下子也记不住,不过基本都自己敲了代码试了试。

os模块

os模块介绍了一些操作系统级别的方法

os.getcwd():得到当前工作目录
os.chdir():改变工作目录
os.system('mkdir haha'):创建文件夹haha

字符串正则匹配

导入re模块,调用findall方法,即可进行正则表达式匹配

>>> re.findall(r'f[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']

数学

import math
可以调用数学里常用的方法,比如三角函数,随机数等等

访问互联网

from urllib.request import urlopen
这个urlopen函数可以返回一个网页的代码

日期和时间

from datetime import date
今天 today = datetime.date.today()
昨天 yesterday = today - datetime.timedelta(days=1)
上个月 last_month = today.month - 1 if today.month - 1 else 12
当前时间戳 time_stamp = time.time()
时间戳转datetime datetime.datetime.fromtimestamp(time_stamp)
datetime转时间戳 int(time.mktime(today.timetuple()))
datetime转字符串 today_str = today.strftime("%Y-%m-%d")
字符串转datetime today = datetime.datetime.strptime(today_str, "%Y-%m-%d")
补时差 today + datetime.timedelta(hours=8)

数据压缩

import zlib
zlib.compress()压缩字符串
zlib.decompress()解压字符串

性能度量

from timeit import Timer
比如交换两个变量
Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
Timer('a,b = b,a', 'a=1; b=2').timeit()
可以算出下边的快一点

原文地址:https://www.cnblogs.com/funmary/p/13441824.html