Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python format() function

Reference for Python format(): format a single value with a format spec, the mini-language for width, alignment, precision and bases, and __format__ for custom classes.

format(value, spec) converts one value to a string according to a format specification. It is the function behind f-string fields and str.format(): f"{x:>8.2f}" ends up calling format(x, ">8.2f").

Each type interprets the spec itself through its __format__() method. Numbers, strings and dates all share a family of rules known as the format specification mini-language, and your own classes can define their own.

Python
print(format(3.14159, ".2f"))
# 3.14

Try it

Python The format spec mini-language

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Custom __format__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
format(value, format_spec="")
Name Description
value The object to format.
format_spec A string like "[[fill]align][sign][z][#][0][width][grouping][.precision][type]". An empty string means "the default", which usually equals str(value).

Common spec parts:

Part Meaning
< > ^ Left, right and center alignment within the width.
+ / space Always show a sign / leave room for one.
, or _ Thousands separator.
.N Digits after the point for floats, maximum length for strings.
d x o b Integer as decimal, hex, octal or binary (# adds the prefix).
f e g % Fixed-point, exponent, general and percentage floats.

Return value: a string.

Raises: ValueError for a spec the type does not understand, TypeError if __format__ returns something other than a string or the spec is not a string.

Usage notes

  • Same engine everywhere. The text after the colon in an f-string or "{:...}".format() is exactly the format_spec.
  • Type decides. format("text", "d") raises ValueError, because strings accept only string codes. Numbers accept numeric codes.
  • Default alignment. Numbers align right and strings align left unless you say otherwise.
  • object.__format__ accepts only an empty spec and raises TypeError for anything else, so custom classes need their own __format__() to support specs.
  • Rounding of floats uses round-half-even on the exact binary value, so format(2.675, ".2f") gives 2.67.
  • Prefer f-strings in everyday code and use format() when the spec itself is computed or you are formatting a lone value.