Sub topic 14
Formatting output with f-strings
This chapter assumes you can write string literals, call print(), and know the difference between int, float, and str. You should also know that a float is a binary approximation. The chapter covers the full f-string syntax, the format specification mini-language, and the errors people hit most often. It does not cover bytes or encoding.
What an f-string is
An f-string is a string literal with an f prefix. Inside it, each pair of braces is a replacement field. Python evaluates the expression in the field when the line runs, converts the result to text, and builds a new str.
name = "Ada"
total = 1234.5
print(f"{name}: {total:,.2f}")
print(f"{total * 2:,.1f} after doubling")
print(f"{name.upper()!r}")This prints:
Ada: 1,234.50
2,469.0 after doubling
'ADA'A replacement field has up to three parts after the expression:
The expression is ordinary Python. The conversion is !r, !s, or !a. The format spec follows a colon and tells the value how to render itself.
Expressions, not just names
Any expression works: arithmetic, method calls, indexing, conditionals, and function calls.
items = {"apple": 3, "kiwi": 12}
count = items["kiwi"]
print(f"{count * 2} kiwis")
print(f"{'many' if count > 5 else 'few'} kiwis")
print(f"{items['apple']} apples")Python versions before 3.12 do not let you reuse the quote character that delimits the f-string inside a field. That is why the last line uses 'apple' inside double quotes. Python 3.12 lifted this restriction, but using different quote styles still works everywhere. Pre-3.12 versions also reject a backslash inside the expression part.
Keep fields short. If the expression needs more than a call or two, compute it on its own line first and put the result in a variable.
The format specification mini-language
After the colon, the spec has this general shape, and every part is optional:
[[fill]align][sign][#][0][width][grouping][.precision][type]
| Part | Examples | Meaning |
|---|---|---|
| fill and align | `*^10`, `<8`, `>8` | Pad character, then `<` left, `>` right, `^` center |
| sign | `+`, `-`, space | Show sign on positives, or only on negatives, or a space for positives |
| `#` | `#x`, `#b` | Add the `0x` or `0b` prefix |
| `0` | `05d` | Pad numbers with zeros after the sign |
| width | `10` | Minimum field width |
| grouping | `,` or `_` | Thousands separator |
| precision | `.2f`, `.3` | Digits after the point for floats, maximum length for strings |
| type | `d`, `f`, `e`, `%`, `x`, `b`, `s` | How to present the value |
Numbers align right by default and strings align left. Here are the most useful combinations:
print(f"{3.14159:.2f}")
print(f"{1234567:,}")
print(f"{1234567:_}")
print(f"{0.256:.1%}")
print(f"{12345.678:.2e}")
print(f"{255:x} {255:#X} {255:#b}")
print(f"{42:+d}")
print(f"{5:03d}")
print(f"|{'hi':*^10}|")
print(f"|{'hi':>6}|")The output is:
3.14
1,234,567
1_234_567
25.6%
1.23e+04
ff 0XFF 0b11111111
+42
005
|****hi****|
| hi|The % type multiplies by 100 and appends a percent sign, so you pass the fraction (0.256), not 25.6.
Dynamic widths and precision
A spec can contain nested fields. This lets you pick width or precision at run time:
value = 3.14159
width = 10
precision = 3
print(f"|{value:{width}.{precision}f}|")This prints | 3.142|. Only one level of nesting is allowed.
Building a table
Alignment and width make columns line up. This is the most common practical use of format specs:
rows = [("apple", 3, 0.5), ("kiwi", 12, 0.25)]
for item, qty, price in rows:
print(f"{item:<8}{qty:>4}{price:>8.2f}")apple 3 0.50
kiwi 12 0.25If a value is longer than the width, Python does not truncate it. The column simply grows, and your table shifts. Use a string precision such as {item:<8.8} if you need a hard cut.
Conversions: `!r`, `!s`, `!a`
By default, the field calls format(value, spec). A conversion applies a function to the value before the spec runs:
!sappliesstr().!rappliesrepr(), which shows quotes and escapes.!aappliesascii(), which is likerepr()but escapes non-ASCII characters.
s = "tab\there"
print(f"{s}")
print(f"{s!r}")
print(f"{'café'!a}")Use !r in logs and error messages. It makes whitespace and empty strings visible, which str() hides.
Self-documenting fields with `=`
Adding = after the expression (Python 3.8+) prints the expression text, an equals sign, and the value's repr(). A spec can follow it.
x = 7
total = 1234.5
print(f"{x=}")
print(f"{x * 2 = }")
print(f"{total=:.1f}")x=7
x * 2 = 14
total=1234.5This is a quick way to inspect values while debugging. Spaces around = are kept exactly as you type them.
Literal braces and dates
To print a brace, double it. Objects can define their own format specs. The datetime type uses strftime codes:
from datetime import datetime
x = 7
d = datetime(2026, 11, 26, 10, 52)
print(f"{{literal}} {x}")
print(f"{d:%Y-%m-%d %H:%M}"){literal} 7
2026-11-26 10:52Common errors and gotchas
Format type does not match the value
Each type code accepts only certain kinds of value. Mismatches raise ValueError:
for value, spec in [(3.5, "d"), ("abc", ",")]:
try:
print(f"{value:{spec}}")
except ValueError as e:
print(type(e).__name__)Both lines print ValueError. d is for integers only, and , is for numbers only. Convert first (int(3.5)) or choose a type that fits (.1f).
Forgetting the `f`
Without the prefix, the braces are plain text:
name = "Ada"
print("{name}")
print(f"{name}")This prints {name} and then Ada. No error is raised, which makes the mistake easy to miss.
Rounding follows the stored binary value
Format specs round the actual value stored, not the decimal you typed. 2.675 is stored as slightly less than 2.675, so it rounds down. Exact halves, such as 0.5, 1.5, and 2.5, round to the nearest even digit.
from decimal import Decimal
print(f"{2.675:.2f}")
print(f"{Decimal('2.675'):.2f}")
print(f"{0.5:.0f} {1.5:.0f} {2.5:.0f}")2.67
2.68
0 2 2For money, hold values as Decimal built from strings. Format specs work on Decimal too.
An f-string is evaluated immediately
You cannot store an f-string as a template and fill it in later, because Python evaluates the fields where the literal appears. For a reusable template, use str.format():
template = "{name} owes {amount:.2f}"
print(template.format(name="Ada", amount=3))This prints Ada owes 3.00. The same mini-language applies, so everything you learned above transfers.
Summary of decisions
- Use an f-string for output that is built and shown right away.
- Use
str.format()when the template is stored or loaded from elsewhere. - Use
!ror=when you want to see exactly what a value is. - Use
Decimalfor exact decimal rounding. A format spec on afloatcannot fix a representation error.
Exercise
What does print(f"{7:*>5}|{0.125:.1%}") print, and why?
Show answer
It prints ****7|12.5%. The spec *>5 right-aligns 7 in a field of width 5 and fills the remaining four spaces with *. The spec .1% multiplies 0.125 by 100 to get 12.5 and shows one decimal place followed by a percent sign.
Exercise
A learner writes f"{2.675:.2f}" and expects 2.68, but gets 2.67. Explain why, and show one way to get 2.68.
Show answer
The float 2.675 is stored in binary as a value slightly below 2.675, so rounding to two places gives 2.67. Build the number as an exact decimal instead: from decimal import Decimal and then f"{Decimal('2.675'):.2f}", which gives 2.68.
Exercise
What is the difference between f"{s}" and f"{s!r}" when s = "a b", and when would you use the second form?
Show answer
The first inserts a b. The second inserts 'a b', with quotes, because !r applies repr(). Use !r in logs and error messages so that whitespace, empty strings, and escape characters are visible.