Python format() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, format(value, spec) converts one value to text using a format spec such as ".2f" (two decimals), "," (thousands separator), or ">8" (right-align in 8 characters). With no spec it behaves like str().

The spec is the same mini-language used after the colon in f-strings and str.format(): format(x, ".2f") equals f"{x:.2f}". Each type decides what its spec means through __format__(), which is why dates accept codes like %Y.

format() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass the value and a spec string.

python
text = format(value, format_spec)
# [[fill]align][sign][#][0][width][,][.precision][type]
CallWhat it does
format(3.14159, ".2f")Returns "3.14".
format(1234567, ",")Returns "1,234,567".
format(0.256, ".1%")Returns "25.6%".
format("hi", "*^6")Returns "**hi**": centered with a fill character.

Align with < (left), > (right), or ^ (center); numbers align right and text aligns left by default.

Library declarations
python
format(value, format_spec="", /)
# calls type(value).__format__(value, format_spec)

Parameters

ParameterDescription
valueRequired. The value to format.
format_specOptional. A format spec string. Default "", which gives the same result as str(value) for most types.

Return Value

Return ValueDescription
strThe formatted text.

Python Examples

Example 1 — Decimals, Separators, Percent, and Bases

Format six numbers with the most common spec codes.

python
pi = 3.14159265

print(format(pi, ".2f"))
print(format(1234567.891, ",.2f"))
print(format(0.256, ".1%"))
print(format(42, "05d"))
print(format(255, "x"), format(255, "#b"))
print(format(1500000, ".2e"))

How It Works

  1. Fixed decimals. .2f rounds to two places: 3.14.
  2. Thousands separator. ,.2f adds commas and keeps two decimals.
  3. Percent. .1% multiplies by 100 and adds a percent sign with one decimal.
  4. Zero padding, bases, exponent. 05d pads to five digits, x and #b switch base, and .2e uses scientific notation.

Example 2 — Line Up a Price Table

Use widths and alignment to print columns that line up, then center a footer with a fill character.

python
rows = [("Apple", 1.5, 3), ("Banana", 0.25, 12), ("Cherry", 10.0, 1)]

print(format("Item", "<8") + format("Price", ">7") + format("Qty", ">5"))
for name, price, qty in rows:
    print(format(name, "<8") + format(price, ">7.2f") + format(qty, ">5d"))
print(format("end", "*^20"))

How It Works

  1. Fixed widths. Every column has a width (8, 7, 5), so each line has the same length.
  2. Text left, numbers right. <8 left-aligns names and >7.2f right-aligns prices with two decimals.
  3. Same spec per column. The header uses the same widths as the rows, so the titles sit above their values.
  4. Fill and center. *^20 centers "end" in 20 characters padded with stars.

Example 3 — Format Dates and Your Own Classes

See how a type defines its own spec language: date uses strftime codes, and a custom class adds a "usd" spec.

python
from datetime import date


class Money:
    def __init__(self, amount):
        self.amount = amount

    def __format__(self, spec):
        if spec == "usd":
            return "USD " + format(self.amount, ",.2f")
        return format(self.amount, spec)


day = date(2024, 3, 9)
print(format(day, "%Y-%m-%d"))
print(format(day, "%d %b %Y"))
print(f"{day:%A}")

price = Money(1234.5)
print(format(price, "usd"))
print(f"{price:.1f}")

How It Works

  1. Type-specific specs. date.__format__ treats the spec as strftime codes, so %Y-%m-%d gives an ISO date.
  2. Same in f-strings. f"{day:%A}" passes "%A" to the same method and prints the weekday.
  3. Your own spec. Money.__format__ recognises "usd" and adds a currency label and separators.
  4. Delegate the rest. Any other spec, like .1f, is passed on to the float's own formatting.

Frequently Asked Questions

Use format(x, ".2f") or f"{x:.2f}". Both return a string such as "3.14".
Use the comma option: format(1234567, ",") returns "1,234,567"; add .2f for decimals: format(x, ",.2f").
format(value, spec) formats one value. "...".format(a, b) fills placeholders in a template. Both use the same spec mini-language.
Use a zero and a width: format(7, "03d") returns "007". f"{7:03d}" does the same.
Define __format__(self, spec) and return a string. Delegate unknown specs to format() on an inner value.

Next: frozendict()

Immutable, hashable mapping (new in Python 3.15).

frozendict() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful