【Python 高频 API 速学 ③】
一、为什么先学这 5 个?
• 它们覆盖了「切 → 洗 → 拼 → 换 → 排版」整条链路。
• 任意一段文本处理脚本,80 % 的操作都能用这 5 个方法写完。
二、五虎上将一览
方法 | 作用 | 典型场景 | 易踩的坑 |
---|---|---|---|
split(sep=None) | 按分隔符切成列表 | 日志拆字段、CSV 解析 | 连续分隔符会产生空串 |
strip(chars=None) | 去首尾空白/指定字符 | 清洗用户输入、去换行 | 只能去首尾,中间不动 |
join(iterable) | 用指定字符串把列表拼回去 | 路径拼接、SQL 占位符 | 元素必须全是 str |
replace(old, new, count=-1) | 批量替换子串 | 脱敏、模板渲染 | 默认全部替换,count 可限次 |
format / f-string | 格式化输出 | 日志、报表、邮件 | 旧版 % 格式化已过时 |
三、一行代码场景秀
- 把网址参数变字典
params = dict(pair.split('=', 1) for pair in query.strip('&').split('&') if pair)
- 清洗并重组文件路径
clean_path = '/'.join(part.strip() for part in raw.split('/') if part)
- 日志脱敏:手机号中间四位换成 ****
masked = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', text)
(先用 replace 也行:text.replace(text[3:7], '****')
)
- 批量生成 SQL 占位符
placeholders = ', '.join(['%s'] * len(columns))
sql = f"INSERT INTO {table} ({', '.join(columns)}) VALUES ({placeholders})"
- 模板邮件格式化
body = """
Hi {name},Your order #{order_id} has been shipped on {date}.
""".format(name=name, order_id=oid, date=ship_date)
或更现代的 f-string:
body = f"Hi {name}, your order #{oid} shipped on {ship_date:%Y-%m-%d}"
四、mini 实战:5 行搞定 nginx 日志转 CSV
输入:空格分隔的原始日志行
输出:ip, time, method, url, status, size
import csv, sys
for line in sys.stdin:parts = line.strip().split()csv.writer(sys.stdout).writerow([parts[0], parts[3][1:], parts[5][1:], parts[6], parts[8], parts[9]])
跑一下:
$ tail -n 100 access.log | python log2csv.py > log.csv
五、一条记忆口令
“split 分,strip 洗,join 拼,replace 换,format 美。”