Nested formatting

suggest change

Some formats can take additional parameters, such as the width of the formatted string, or the alignment:

>>> '{:.>10}'.format('foo')
'.......foo'

Those can also be provided as parameters to format by nesting more {} inside the {}:

>>> '{:.>{}}'.format('foo', 10)
'.......foo'
'{:{}{}{}}'.format('foo', '*', '^', 15)
'******foo******'

In the latter example, the format string '{:{}{}{}}' is modified to '{:*^15}' (i.e. “center and pad with * to total length of 15”) before applying it to the actual string 'foo' to be formatted that way.

This can be useful in cases when parameters are not known beforehand, for instances when aligning tabular data:

>>> data = ["a", "bbbbbbb", "ccc"]
>>> m = max(map(len, data))
>>> for d in data:
...     print('{:>{}}'.format(d, m))
      a
bbbbbbb
    ccc

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents