Python Language String Formatting Nested formatting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any Python Language Question?