【问题标题】:How do I fill out Python string templates from a config file?如何从配置文件中填写 Python 字符串模板?
【发布时间】:2021-07-12 16:27:19
【问题描述】:

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

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

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

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

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

KeyError: 'year'

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

【问题讨论】:

    标签: python string config keyerror


    【解决方案1】:

    使用关键字参数将值传递给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'
    

    【讨论】:

    • 感谢朋友!那行得通,我完全忘记了 kwargs。
    【解决方案2】:

    您只需将模板更改为:

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多