一日一技:字符串Format忽略缺失的字段

开发 前端
当项目代码规模变大以后,很容易出现传入的字典缺少值的情况。有没有办法让Python在遇到.format参数缺值的时候,自动忽略呢?

在一些大型项目的开发中,我们需要创建很多字符串模板,然后在需要的时候填入对应的信息。例如:

template_1 = '缺少参数:{field_name}'
template_2 = '网页请求失败,url: {url},状态码:{status},返回信息:{resp}'
template_3 = '其他未知错误:{e}'

当我们代码中遇到异常时,用字典的形式,返回格式化字符串所需要的字段,然后在一个专门的函数中统一组装报错信息,例如:

def make_request(url):
resp = requests.get(url)
if resp.status != 200:
err_msg_field = {'url': url, 'status': status, 'resp': resp.text}
raise RequestFail(err_msg_field=err_msg_field)
return resp.json()

try:
result = make_request(url)
except RequestFail as e:
msg = template_2.format(**e.err_msg_field)
...用日志或者其他方式输出报错信息...
except Exception as e:
msg = template_3.format(e=e)

但.format有一个问题:参数中的字段可以比字符串实际需要的多,但不能少。例如:

图片

也可以直接使用字典来传入:

图片

如果字符串模板里面需要某个key,但是.format传入的参数又没有这个key,代码就会报错。

当项目代码规模变大以后,很容易出现传入的字典缺少值的情况。有没有办法让Python在遇到.format参数缺值的时候,自动忽略呢?

如果你使用Python 3,那么可以使用.format_map配合defaultdict来实现:

from collections import defaultdict
template_2 = '网页请求失败,url: {url},状态码:{status},返回信息:{resp}'
data = defaultdict(str, {'url': 'https://www.kingname.info', 'status': 500})
msg = template_2.format_map(data)
print(msg)

运行效果如下图所示:

图片

如果你使用的是Python 2,那么可以这样写:

from collections import defaultdict
import string
string.Formatter().vformat
template_2 = '网页请求失败,url: {url},状态码:{status},返回信息:{resp}'
data = defaultdict(str, {'url': 'https://www.kingname.info', 'status': 500})
msg = string.Formatter().vformat(template_2, (), data)
print msg

运行效果如下图所示:

图片

本文转载自微信公众号「未闻Code」,可以通过以下二维码关注。转载本文请联系未闻Code公众号。

责任编辑:武晓燕 来源: 未闻Code
相关推荐

2021-10-20 20:02:47

字符变量函数

2022-06-20 19:37:59

Python字符串HTML

2021-11-03 20:16:49

匹配Python字符

2021-05-08 19:33:51

移除字符零宽

2021-04-27 22:15:02

Selenium浏览器爬虫

2021-10-15 21:08:31

PandasExcel对象

2021-04-05 14:47:55

Python多线程事件监控

2022-06-28 09:31:44

LinuxmacOS系统

2022-03-12 20:38:14

网页Python测试

2021-04-12 21:19:01

PythonMakefile项目

2021-03-12 21:19:15

Python链式调用

2021-09-13 20:38:47

Python链式调用

2023-10-28 12:14:35

爬虫JavaScriptObject

2021-04-19 23:29:44

MakefilemacOSLinux

2022-03-07 09:14:04

Selenium鼠标元素

2021-10-03 20:08:29

HTTP2Scrapy

2021-07-27 21:32:57

Python 延迟调用

2021-02-14 22:22:18

格式图片 HTTP

2023-10-29 09:16:49

代码安全命令

2021-05-13 09:01:51

Cloud Flare浏览器网站
点赞
收藏

51CTO技术栈公众号