Search code examples
pythonstring-formatting

Does 'string.format' allow more control over iterables / dictionaries?


I am in a situation where it is easy to adjust the formatting string, but hard to adjust the arguments for format:

'I can influence this'.format(foo={'a': 'no', 'b': 'control'},
                              bar=['no', 'control', 'either'])

For numbers, you can format with {:1.23f}.

For dates, you can format with {:%Y-%m-%d}.

I would like to have more control for iterables and for dictionaries. For example, I could imagine '{:iterable.42}' to access the 43st element of an iterable and {:dict.b} to access the element with the key b.

Does something like that exist?


Solution

  • You can access to keyword arguments specified in the function format while formatting your string:

    '{foo[a]} {bar[1]}'.format(foo={'a': 'no', 'b': 'control'},
                                  bar=['no', 'control', 'either'])
    

    A useful source for formatting string in python: https://pyformat.info/