🔢 Printing numbers as strings


This will be a short one, but f-strings are too useful.

>>> num = 123.456789
>>> f"{num:0>12.2f}"
'000000123.46'

What's going on here? f""
is an f-string, a kind of "string" in which variables can appear directly in the string, contained in {brackets}.

There are two things going into the brackets, the variable num and the formatting parameters 0>12.2f, appearing after the colon :. The variable is automatically converted to a string here, and the formatting parameters, including the colon can be omitted.

The first symbol 0 is the fill symbol, which indicates the symbol that will be used for fixed-length strings.

The second symbol > is the alignment of the string, which indicates right-alignment, but this can also be left-aligned with < or centered with ^. By default, the variable is right-aligned, so this can be omitted.

The third part 12 indicates the minimum string length. In this case the string is padded with zeros on the left (because of the right-alignment) if the string is shorter than 12 letters. The fill symbol is a space ( ) by default.

The fourth part consists of .2 and f, which is the precision and the format. In thise case we want two digits after the decimal, and in the fixed-point notation.

The Python docs contains the full format specification.

– &.