format()

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:

Python
>>> format(1234.5678, ",.2f")
'1,234.57'

format() Signature

Python Syntax
format(value, format_spec="")

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_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:

Python
>>> format(1234.5678, ".2f")
'1234.57'

With an integer number and a format specifier for thousand separators:

Python
>>> format(1000000, ",d")
'1,000,000'

With a string and a format specifier for left alignment and filling:

Python
>>> format("Hello", "<20")
'Hello               '

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:

Python
>>> sales = 12345678.9
>>> formatted_sales = format(sales, "$,.2f")
>>> print(f"Total Sales: {formatted_sales}")
Total Sales: $12,345,678.90

In this example, the format() function formats the sales amount with a dollar sign, a comma as a thousand separator, and two decimal places. This helps present financial data clearly and professionally.

Tutorial

Python String Formatting: Available Tools and Their Features

In this tutorial, you'll learn about the main tools for string formatting in Python, as well as their strengths and weaknesses. These tools include f-strings, the .format() method, and the modulo operator.

basics best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader