Python实战速查:场景驱动+口诀记忆 在学习 Python 实战应用时面对层出不穷的方法和第三方库我们常常陷入“会用但写不健壮懂点但效率不高”的困境。要打破这一瓶颈关键在于建立一个系统化的知识索引体系帮助我们在遇到问题时快速定位最优解。本文提出一种“场景驱动 口诀记忆”的实践框架将常见问题按实际开发场景归类再辅以精炼口诀强化核心要点让你在遇到类似需求时能立刻联想到对应解法真正做到“见招拆招快速上手”。 Python 快速索引库使用说明遇到问题 → 找到对应场景 → 看推荐方案 → 复制代码模板 核心口诀先记这个字符串用自带法文件路径找path 网络请求用requests数据格式有专属 日期时间datetime正则处理用re 系统操作看os高级并发asyncio。1️⃣ 字符串处理String场景速查表你想做什么一句话方案代码模板按分隔符切割split()a,b,c.split(,)→[a,b,c]按分隔符切割保留分隔符partition()a,b,c.partition(,)→(a,,,b,c)去除首尾空格strip() hello .strip()→hello查找子串位置find()/index()hello.find(e)→1替换内容replace()hello.replace(e,a)→hallo判断开头/结尾startswith()/endswith()file.txt.endswith(.txt)→True大小写转换upper()/lower()Hello.lower()→hello拼接多个字符串join(),.join([a,b])→a,b格式化输出f-stringf姓名:{name}检查是否纯数字isdigit()123.isdigit()→True 高频组合技# 提取URL域名你刚学的protocolurl.split(://)[0]domainurl.split(://)[1].split(/)[0]# 清理用户输入cleanuser_input.strip().lower()# 解析键值对itemsa1b2.split()foriteminitems:key,valueitem.split()2️⃣ 文件与路径File Path场景速查表你想做什么一句话方案代码模板拼接路径跨平台pathlib.PathPath(folder) / file.txt读取文本文件with open()with open(file.txt) as f: data f.read()写入文本文件with open(w)with open(file.txt,w) as f: f.write(内容)检查文件是否存在Path.exists()Path(file.txt).exists()获取文件名Path.namePath(/a/b.txt).name→b.txt获取文件扩展名Path.suffixPath(b.txt).suffix→.txt遍历文件夹Path.glob()list(Path(.).glob(*.py))创建文件夹Path.mkdir()Path(new_folder).mkdir(exist_okTrue)获取当前路径Path.cwd()Path.cwd()→ 当前目录删除文件Path.unlink()Path(file.txt).unlink() 记忆口诀路径操作用path跨平台不烦恼 读写文件用with自动关闭记得牢。3️⃣ 网络与请求Network场景速查表你想做什么一句话方案代码模板解析URLurlparse()from urllib.parse import urlparseURL参数编码urlencode()urlencode({name:张三})发送GET请求requests.get()requests.get(https://api.com)发送POST请求requests.post()requests.post(url, jsondata)添加请求头headers参数requests.get(url, headers{User-Agent:...})处理超时timeout参数requests.get(url, timeout5)处理代理proxies参数requests.get(url, proxies{http:...}) 安装第三方库pipinstallrequests# 比urllib好用10倍 记忆口诀URL解析用parse网络请求用requests GET获取POST送headers头里放信息。4️⃣ 数据格式处理Data Format场景速查表格式核心操作代码模板JSON→ 字符串json.dumps()json.dumps({name:张三})JSON← 字符串json.loads()json.loads({name:张三})JSON→ 文件json.dump()json.dump(data, file)JSON← 文件json.load()json.load(file)CSV读取csv.reader()csv.reader(open(file.csv))CSV写入csv.writer()csv.writer(open(file.csv,w)) 实战模板importjson# API返回JSON → Python字典responserequests.get(https://api.com/data)dataresponse.json()# 自动解析JSON# Python字典 → JSON字符串json_strjson.dumps(data,ensure_asciiFalse,indent2)# 读取JSON文件withopen(config.json)asf:configjson.load(f)5️⃣ 日期与时间DateTime场景速查表你想做什么代码模板获取当前时间from datetime import datetime; now datetime.now()格式化时间now.strftime(%Y-%m-%d %H:%M:%S)字符串→时间datetime.strptime(2026-07-19, %Y-%m-%d)时间加减from datetime import timedelta; now timedelta(days1)时间差计算(end - start).days获取时间戳now.timestamp() 常用格式符%Y2026# 年4位%y26# 年2位%m07# 月%d19# 日%H14# 小时24小时制%I02# 小时12小时制%M30# 分钟%S45# 秒%pPM# AM/PM%aMon# 星期缩写%AMonday# 星期全称 记忆口诀now datetime.now()strftime格式化 strptime反解析timedelta算加减。6️⃣ 列表与字典操作List Dict高频操作想做什么代码说明列表推导式[x*2 for x in range(5)]快速生成列表字典取值安全dict.get(key, 默认值)避免KeyError列表去重list(set(my_list))转为集合再转回合并两个字典{**dict1, **dict2}Python 3.5列表排序sorted(list)/list.sort()返回新列表/原地排序字典遍历for key, value in dict.items():同时获取键和值列表反转list[::-1]/list.reverse()切片/原地反转查找最大/最小max(list)/min(list)也可用于字典 高级技巧# 列表去重并保持顺序list(dict.fromkeys([1,2,2,3]))# [1,2,3]# 字典合并Python 3.9dict1|dict2# 更简洁# 安全获取嵌套字典data.get(user,{}).get(name,未知)7️⃣ 异常处理Exception标准模板try:# 可能出错的代码resultrisky_operation()exceptValueErrorase:# 值错误print(f值错误:{e})exceptKeyErrorase:# 键错误print(f键不存在:{e})exceptExceptionase:# 其他所有异常print(f未知错误:{e})else:# 没有异常时执行print(成功)finally:# 无论如何都执行cleanup()常见异常类型异常场景ValueError类型对但值不对如 int(“abc”)KeyError字典键不存在IndexError列表索引超出范围FileNotFoundError文件不存在ConnectionError网络连接失败TimeoutError操作超时8️⃣ 正则表达式Regex常用模式importre# 提取所有数字re.findall(r\d,我有3个苹果和5个梨)# [3,5]# 提取邮箱re.findall(r\S\S,我的邮箱是 abcexample.com)# 匹配手机号简单版re.match(r^1\d{10}$,13800138000)# 替换re.sub(r\d,X,我3岁)# 我X岁# 常用符号\d数字 \w字母数字 \s空格1个或多个*0个或多个 ?0或1个9️⃣ 常用标准库速查模块用途记忆点random随机数random.randint(1,10)math数学运算math.sqrt(16)→ 4.0os操作系统os.getcwd()当前目录sys系统参数sys.argv命令行参数time时间相关time.sleep(1)延迟1秒copy拷贝对象copy.deepcopy()深拷贝collections高级容器Counter()计数itertools迭代器工具chain(),cycle()functools函数工具lru_cache()缓存 第三方库必装# 数据科学pipinstallnumpy pandas matplotlib# 网络爬虫pipinstallrequests beautifulsoup4 scrapy# Web开发pipinstallflask django fastapi# 数据库pipinstallpymongo redis# 图像处理pipinstallpillow opencv-python# 机器学习pipinstallscikit-learn torch tensorflow# 工具pipinstalltqdm# 进度条pipinstallpython-dotenv# 环境变量 快速记忆卡片最常用的10个导入importjson# JSON处理importre# 正则importos# 系统操作importsys# 系统参数importrandom# 随机数frompathlibimportPath# 路径操作推荐fromdatetimeimportdatetime# 日期时间fromurllib.parseimporturlparse# URL解析importrequests# HTTP请求第三方importpandasaspd# 数据分析第三方调试三板斧print(调试信息)# 最简单的importpdb;pdb.set_trace()# 断点调试importlogging# 日志记录 索引库使用流程遇到问题 ↓ 查这个索引库 → 找对应场景 ↓ 复制代码模板 ↓ 根据实际情况修改 ↓ 解决问题✅