The built-in format()
function converts an input value into a formatted string representation based on the specified format. The function takes a format specification, format_spec
, which determines how the value should be formatted:
format()
Signature Arguments Argument Description Default Value value
The value to be formatted. Required argument format_spec
A string specifying the format using the mini-language syntax. ""
Return Value
format_spec
isn’t provided, then format()
returns the string representation of the value as if str(value)
was called.format()
Examples
With a floating-point number and a format specifier for two decimal places:
With an integer number and a format specifier for thousand separators:
With a string and a format specifier for left alignment and filling:
format()
Common Use Cases
The most common use cases for the format()
function include:
format()
Real-World Example
Suppose you’re creating a financial report and need to format currency values consistently. Here’s how you can use the format()
function to achieve that:
In this example, the format()
function formats the sales amount with a comma as a thousand separator and two decimal places. Then, you add a dollar sign using an f-string. This helps present financial data clearly and professionally.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4