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
| Parameter | Description |
|---|---|
value |
The value to format. |
format_spec optional |
A format specification such as ".2f", ",", ">10" or "%". Default: "" |
Return value
A formatted str.
Examples
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
for name, price in [("Tea", 2.5), ("Cake", 12)]:
print(format(name, "<8") + format(price, ">8.2f"))
Output
Tea 2.50 Cake 12.00
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.repr()· Return the developer-friendly string representation of an object, often valid Python code that recreates the value.round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).- Python String Formatting · tutorial