10. Format values into text

Formatting turns a value into text with a chosen layout. The built-in function is:

  • value — the value to format, usually a number.
  • format_spec — a short text that describes the layout. Default: "", which gives the same text as str(value).

An f-string accepts the same spec after a colon: f"{value:format_spec}".

The parts of a spec used in this lesson:

SpecMeaningExampleResult
.2ffixed-point number with 2 digits after the decimalformat(2.5, ".2f")2.50
>10width 10, aligned to the rightf"({'Python':>10})"( Python)
<10width 10, aligned to the leftf"({'Python':<10})"(Python )
,comma as thousands separatorf"{1234567:,}"1,234,567

The width is a minimum: the value is padded with spaces (the default fill) until it is that wide. Alignment can be combined with precision: >8.2f means width 8, right-aligned, 2 decimals.

format() returns a new string; it does not change the value.

Coming from JavaScript? An f-string is a template literal: f"{x}" is the same idea as ${x} inside backticks. The spec after the colon (.2f, ,, >10) has no direct JS equivalent.

#01

Format with two decimals

format(value, format_spec) returns the text described by format_spec. The spec .2f means a fixed-point number with 2 digits after the decimal point.

Print the result of formatting 3.14159, passing the spec ".2f" as the second positional argument.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

The same layout in an f-string

An f-string accepts the same spec after a colon: f"{value:format_spec}". The .2f spec always keeps two decimals, so it adds a trailing zero when needed.

Print 2.5 using an f-string with the spec .2f.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Align to the right

Inside a spec, > aligns to the right and the number after it is the minimum width. Short text is padded with spaces on the left.

Print "Python" right-aligned in a width of 10 using an f-string, between parentheses.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Align to the left

< aligns to the left and pads with spaces on the right.

Print "Python" left-aligned in a width of 10 using an f-string, between parentheses.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Add thousands separators

A comma , in the spec groups the digits of a number in threes.

Print 1234567 using an f-string with the spec ,.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

Combine width and precision

The parts of a spec can be written together. >8.2f means width 8, aligned to the right, with 2 decimals.

Print 3.5 using an f-string with the spec >8.2f, between parentheses.

Print exactly:

Create a free account to save your progress and unlock chapter 2.