Python Function Reference

format

Format a value according to a format specification.

Python 3.13
format(value[, format_spec])
  • [ ]optional part
value
The value to format.
Any
format_spec
The format specification, as after the colon in an f-string: ".2f", ",", "08b", ">10" and so on; without it, str(value).
strOptional

Return value

A string.

Examples

Two decimal places

Python 3.13
print(format(3.14159, '.2f'))
3.14

Thousands separator

Python 3.13
print(format(1234567.891, ',.1f'))
1,234,567.9

Binary number and percent

Python 3.13
print(format(42, '08b'), format(0.25, '.0%'))
00101010 25%

Details

format(value, spec) is the same as f"{value:spec}". Common formats: .2f for two decimal places, , for a thousands separator, % for percent, 08b for an eight-digit binary number, >10 and <10 for alignment to a width.

See also