Next / Previous / Contents / TCC Help System / NM Tech homepage

9.4.5. Formatting a field of variable length

Sometimes you need to format a field using a length that is available only once the program is running. To do this, you can use a number or name in {braces} inside a format code at the width position. This item then refers to either a positional or keyword argument to the .format() method as usual.

Here's an example. Suppose you want to format a number n using d digits. Here are examples showing this with and without left-zero fill:

>>> n = 42
>>> d = 8
>>> "{0:{1}d}".format(42, 8)
'      42'
>>> "{0:0{1}d}".format(42, 8)
'00000042'
>>> 

You can, of course, also use keyword arguments to specify the field width. This trick also works for variable precision.

"{count:0{width}d}".format(width=8, count=42)
'00000042'
>>> 

The same technique applies to substituting any of the pieces of a format code.

>>> "{:&<14,d}".format(123456)
'123,456&&&&&&&'
>>> "{1:{0}{2}{3},{4}}".format('&', 123456, '<', 14, 'd')
'123,456&&&&&&&'
>>> "{:@^14,d}".format(1234567)
'@@1,234,567@@@'
>>> "{n:{fil}{al}{w},{kind}}".format(
...     kind='d', w=14, al='^', fil='@', n=1234567)
'@@1,234,567@@@'