Python 常用标准库
TIP
Python 标准库覆盖了 JSON、时间、集合、正则等常见需求,无需安装第三方包。
JSON
python
import json
data = {"name": "张三", "age": 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
parsed = json.loads(json_str)日期时间
python
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
date = datetime.strptime("2024-01-01", "%Y-%m-%d")
tomorrow = now + timedelta(days=1)collections
python
from collections import defaultdict, Counter
word_count = defaultdict(int)
for word in ["a", "b", "a", "c", "b", "a"]:
word_count[word] += 1
cnt = Counter("hello world")
print(cnt.most_common(3))re 正则表达式
python
import re
pattern = r"\d{3}-\d{4}-\d{4}"
match = re.search(pattern, "电话: 138-1234-5678")
if match:
print(match.group())