Python 3 reference · Built-in Functions

Python format() Function

Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.

Python 3 Since 3.0

Syntax

format(value, format_spec="")

Parameters

ParameterDescription
value The value to format.
format_spec optional A format specification such as ".2f", ",", ">10" or "%". Default: ""

Return value

A formatted str.

Examples

Common format specsTry it yourself
print(format(3.14159, ".2f"))
print(format(1234567, ","))
print(format(0.256, ".1%"))
print(format(255, "x"), format(255, "08b"))

Output

3.14
1,234,567
25.6%
ff 11111111
Align columnsTry it yourself
for name, price in [("Tea", 2.5), ("Cake", 12)]:
    print(format(name, "<8") + format(price, ">8.2f"))

Output

Tea         2.50
Cake       12.00
format() and f-strings use the same specsTry it yourself
price = 1234.5
print(f"{price:,.2f}")      # the same spec inside an f-string
print(format(price, ",.2f"))

Output

1,234.50
1,234.50

Good to know

The spec after the : in an f-string, f"{x:.2f}", is exactly the format_spec here. Classes can customise it with __format__(); for example dates accept format(date, "%Y-%m-%d").

Version history

VersionChange
Python 3.0Added