如何从配置文件中填写 Python 字符串模板?

How do I fill out Python string templates from a config file?

我在配置文件中有以下模板:

"template": "2.1/files/{year:04d}/{month:02d}/{day:02d}/{hour:02d}"

我想根据函数的输入填写年、月、日和小时。到目前为止我已经尝试过:

test_fill = prefix.format(2021,12,23,14)

其中 prefix 具有上述模板字符串。尝试以上我得到:

KeyError: 'year'

根据我对函数的年、月、日和小时输入修改字符串的正确方法是什么?

使用关键字参数将值传递给 format:

>>> prefix = "2.1/files/{year:04d}/{month:02d}/{day:02d}/{hour:02d}"
>>> prefix.format(year=2021, month=12, day=23, hour=14)
'2.1/files/2021/12/23/14'

>>> (year, month, day, hour) = (2020, 1, 2, 13)
>>> prefix.format(year=year, month=month, day=day, hour=hour)
'2.1/files/2020/01/02/13'

您只需将模板更改为:

tmplt = "2.1/files/{:04d}/{:02d}/{:02d}/{:02d}"
print(tmplt.format(2021, 12, 23, 14))

给出:

2.1/files/2021/12/23/14

您还可以保留模板并更改将输入传递给格式的方式。请参阅下面的字典解包示例:

tmplt = "2.1/files/{year:04d}/{month:02d}/{day:02d}/{hour:02d}"
input = {'year': 2021, 'month': 12, 'day': 23, 'hour': 14}

print(tmplt.format(**input))