标准库概览 (Standard Library Overview)
Python 经常被称为“电池内置” (Battery Included),因为它附带了一个功能极其丰富且强大的标准库,几乎涵盖了你日常开发所需的大部分功能。
我们已经在之前的章节中深入介绍了 sys, os, pathlib, json, csv, collections, itertools, random, heapq 以及 threading 等模块,这里我们快速浏览一些其他极其常用的模块。
1. datetime: 日期与时间处理
处理日期、时间、时区和时间差的核心模块。
from datetime import datetime, timedelta, date
# 1. 获取当前时间
now = datetime.now()
print(f"Current Date: {now}")
# 2. 格式化日期字符串
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted_date}")
# 3. 解析日期字符串 -> datetime 对象
date_str = "2023-01-01"
d = datetime.strptime(date_str, "%Y-%m-%d")
print(f"Parsed: {d}")
# 4. 时间差计算 (例如:7 天后)
future_date = now + timedelta(days=7, hours=2)
print(f"Future: {future_date}")
# 5. 只关心日期和只关心时间
print(date.today()) # 只包含日期
2. re: 正则表达式
正则表达式 (Regular Expression) 是一种强大的文本匹配与提取工具。
import re
text = "Hello, my email is alice@example.com."
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
# 1. 查找第一个匹配项
match = re.search(pattern, text)
if match:
print(f"Found email: {match.group()}")
# 2. 查找所有匹配项
emails = re.findall(pattern, "alice@example.com, bob@mail.org")
print(f"All emails: {emails}")
# 3. 替换文本
new_text = re.sub(r"alice", "bob", text)
print(new_text)
3. logging: 日志记录
不要总是使用 print() 来调试!logging 提供了一个标准的、可扩展的日志记录系统。
import logging
# 1. 配置日志格式、级别和输出位置
logging.basicConfig(
level=logging.INFO, # 只有 INFO 及以上级别会被记录
format='%(asctime)s - %(levelname)s - %(message)s'
)
# 2. 记录日志
logging.debug("This is a debug message") # 不会输出 (debug < info)
logging.info("Starting application...")
logging.warning("Disk space low!")
logging.error("Failed to connect to database.")
logging.critical("System is shutting down!")
4. math: 数学函数
提供了许多基础数学函数,如三角函数、对数、取整等。
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
print(math.floor(3.9)) # 3
print(math.ceil(3.1)) # 4
print(math.pow(2, 3)) # 8.0
5. functools: 高阶函数工具
包含了一些方便的高阶函数。
lru_cache 缓存结果
自动缓存函数的返回值,特别适合计算斐波那契数列等递归函数,能极大提升性能。
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(30)) # 瞬间计算完成,如果不加缓存会很慢
partial 偏函数
固定函数的部分参数,生成一个新的函数。
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2) # 固定第二个参数为 2
cube = partial(power, exp=3) # 固定第二个参数为 3
print(square(5)) # 25
print(cube(2)) # 8
6. random: 随机数生成
虽然第 5 章提到了随机数,这里再次强调几个常用方法。
import random
nums = [1, 2, 3, 4, 5]
print(random.choice(nums)) # 随机选一个元素
print(random.sample(nums, 2)) # 随机选 k 个不重复元素
random.shuffle(nums) # 打乱列表顺序 (原地修改)
print(nums)
print(random.uniform(1.5, 3.5)) # 生成指定范围内的浮点数
总结
Python 标准库是巨大的宝库。当你准备造轮子(写功能)之前,一定要先去翻阅一下官方文档,看看是否已经有“内置电池”实现了相同功能。
下一步
我们已经掌握了 Python 大部分核心特性,但还有一个现代 Web 开发和高性能网络编程必不可少的神器——异步 I/O。