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}")| Code | Meaning | Output here |
|---|---|---|
.2f | 2 decimal places | 3.14 |
,.2f | thousands separators, 2 decimals | 1,234,567.89 |
.1% | a percentage with 1 decimal | 25.6% |
05d | a whole number padded with zeros to 5 digits | 00042 |
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")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}")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
itemsholds three tuples, each with a name, a quantity and a price.- The
forline takes each tuple apart intoname,qtyandprice. {name:<6}shows the name left-aligned in 6 characters.{qty:>3}shows the quantity right-aligned in 3.{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
fbefore the quote: the braces are then printed literally. - Using
.2fon text: format codes likefonly work on numbers. - Expecting
:5to 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
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.