Format specifiers: a quick reference

Published

2023-07-31

Format specifiers: a quick reference

Format specifiers actually constitute a “mini-language” of their own. For a complete reference, see the section entitled “Format Specification Mini-Language” in the Python documentation for strings (https://docs.python.org/3/library/string.html).

Remember that format specifiers are optionally included in f-string replacement fields. The format specifier is separated from the replacement expression by a colon. Examples:

>>> x = 0.16251`
>>> f'{x:.1%}'
'16.3%'
>>> f'{x:.2f}'
'0.16'
>>> f'{x:>12}'
'     0.16251'
>>> f'{x:.3E}'
'1.625E-01'

Here’s a quick reference for some commonly used format specifiers:

option meaning example
< align left, can be combined with width <12
> align right, can be combined with width >15
f fixed point notation, combined with precision .2f
% percentage (multiplies by 100 automatically) .1%
, use thousands separators, for example, 1,000 ,
E scientific notation, combined with precision .4E

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).