format() | Python’s Built-in Functions – Real Python
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
- Returns a formatted string representation of the input value according to the specified format.
- If
format_specisn’t provided, thenformat()returns the string representation of the value as ifstr(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:
- Formatting numbers for better readability, such as adding thousand separators or specifying decimal places.
- Aligning text within a fixed width, using left, right, or center alignment.
- Formatting dates and times in a specific format.
- Preparing data for display in reports or user interfaces.
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:
- Python's Format Mini-Language for Tidy Strings (Tutorial)
- String Interpolation in Python: Exploring Available Tools (Tutorial)
- Python's F-String for String Interpolation and Formatting (Tutorial)
- A Guide to Modern Python String Formatting Tools (Tutorial)
- Python String Formatting Tips & Best Practices (Course)
- Python String Formatting: Available Tools and Their Features (Quiz)
- String Interpolation in Python: Exploring Available Tools (Quiz)
- Python 3's F-Strings: An Improved String Formatting Syntax (Course)
- Python's F-String for String Interpolation and Formatting (Quiz)
- Formatting Python Strings (Course)
- A Guide to Modern Python String Formatting Tools (Quiz)