Present numbers
Display numeric output with controlled precision or notation.
Python · Function
format() converts a value to a formatted string representation. Its optional format specification controls presentation according to the value’s type.
format() converts a value to its formatted string representation. The optional format specification is interpreted by the value’s type, while many built-in types use the standard formatting syntax.
format(value, format_spec='', /)| Name | Type | Description |
|---|---|---|
value | object | The object whose formatted representation is requested. |
format_spec | str | An optional type-dependent formatting specification; it defaults to an empty string. |
A string containing the formatted representation of value.
price = 12.5
print(format(price, ".2f"))
print(format(255, "#x"))Formats a floating-point value to two decimal places and an integer as a prefixed hexadecimal string.
Display numeric output with controlled precision or notation.
Produce identifiers or values in bases such as hexadecimal.
Delegate presentation to an object’s type-specific formatting rules.
format() returns a formatted representation of value as a string. Its optional format_spec controls the presentation, and the value’s type determines how that specification is interpreted.
Follow-up: What happens when format_spec is omitted? It defaults to an empty string, so the type supplies its default representation.
The first argument is the value to format, and the second optional argument is the format specification. The specification is interpreted according to the value’s type.
Follow-up: Why can a specification differ between types? Built-in types may implement different formatting rules even though they share the standard formatting syntax.
format() is a built-in function, so it is available without importing a module. It returns the formatted representation rather than modifying the original value.
Follow-up: How can formatting be embedded in larger text? Use a formatted string literal or another string-formatting mechanism when surrounding text is needed.
str__format__Formatted string literals