Search code examples
pythonstringconfigkeyerror

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


I have the following template in a config file:

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

And I want to fill out the year, month, day, and hour based on inputs to my function. So far I have tried:

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

Where prefix has the template string described above. Trying the above I get:

KeyError: 'year'

What is the correct to way to modify the string based on my year, month, day, and hour inputs to my function ?


Solution

  • Use keyword arguments to pass values to 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'