Formatting output

Introduction

f-strings can do more than drop values into text. A format code after a colon controls width, alignment and decimal places, which is how programs print neat tables and receipts.

A correct answer shown badly is hard to use. Format codes let a program print tables, receipts and reports that people can read at a glance, and they only take a few characters to write.

How it works

Number formats

pi = 3.14159265
big = 1234567.891
print(f"{pi:.2f}")
print(f"{big:,.2f}")
print(f"{0.256:.1%}")
print(f"{42:05d}")
Open in compiler
CodeMeaningOutput here
.2f2 decimal places3.14
,.2fthousands separators, 2 decimals1,234,567.89
.1%a percentage with 1 decimal25.6%
05da whole number padded with zeros to 5 digits00042

Any expression

name = "Nadia"
marks = [72, 85, 90]
print(f"{name} scored {sum(marks)} in total, {sum(marks) / len(marks):.1f} on average")
print(f"{name.upper()} has {len(name)} letters")
Open in compiler

The braces can hold any expression, including function calls and calculations. Keep them short; if an expression gets long, compute it on its own line first.

Syntax

f"{name:<10}"      # left-align in 10 characters
f"{qty:>4}"        # right-align in 4
f"{price:>10.2f}"  # right-align in 10, with 2 decimals
f"{big:,}"         # thousands separators
f"{ratio:.1%}"     # a percentage

Example

items = [("Rice", 2, 68.5), ("Dal", 1, 120), ("Oil", 3, 175.25)]
for name, qty, price in items:
    print(f"{name:<6}{qty:>3}{qty * price:>10.2f}")
Open in compiler

Inside the braces, name:<6 means "left-align in 6 characters", qty:>3 means "right-align in 3", and :>10.2f means "right-align in 10, with 2 decimal places". Every row uses the same widths, so the columns line up in the output panel.

Line by line

  1. items holds three tuples, each with a name, a quantity and a price.
  2. The for line takes each tuple apart into name, qty and price.
  3. {name:<6} shows the name left-aligned in 6 characters.
  4. {qty:>3} shows the quantity right-aligned in 3.
  5. {qty * price:>10.2f} works out the cost, then right-aligns it in 10 with 2 decimals.

Expected result

Rice    2    137.00
Dal     1    120.00
Oil     3    525.75

In the real world

Bank statements, invoices and scientific tables all rely on columns that line up. Command-line tools format their output in the same way, so that people can compare values down a column.

Common mistakes

  • Forgetting the f before the quote: the braces are then printed literally.
  • Using .2f on text: format codes like f only work on numbers.
  • Expecting :5 to cut long text. Width is a minimum; longer values simply take more room.

Best practices

  • Use the same widths on every row of a table.
  • Do long calculations on their own line, then format the result.
  • Choose the width from the longest value you expect.

Summary

A format code after a colon sets the width, alignment, decimals, separators and percentages of a value. .2f gives two decimals, < and > align, and width is only a minimum.

Practice

Print a three-line price list where item names are left-aligned in 12 characters and prices are right-aligned in 8 with two decimals.

Quick check

1. What does f'{7.5:.2f}' produce?
2. What does f'{42:05d}' produce?
3. Which code right-aligns a value in 8 characters?

Key takeaways

  • A format code controls how a value looks, without changing it.
  • < aligns left, > aligns right and ^ centres.
  • Width is a minimum, so long values are not cut.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.