runtime
29 / 250
lesson 29 Strings & Text · beginner

Fill a sentence with values

An f-string puts values straight into text: f"Total: {total:.2f}". The part after the colon controls decimals, widths and separators.

You'll be able to
  • Explain why "Items: " + 3 fails and what an f-string does instead
  • Put any expression in braces, and show money with :.2f
  • Line values up in columns with :<n and :>n
The idea

Receipts, reports and messages mix fixed words with values. Joining with + works only on text, so every number would need str() first, and the spaces are easy to get wrong.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Joining text and a number
qty = 3
print("Items: " + qty)

An f-string has an f right before the opening quote. You write the sentence once and put each value in braces: f"Items: {qty}". Any expression can go inside the braces, such as {qty * price}.

After a colon, a format spec controls how the value looks. {price:.2f} always shows two decimals, which is what money needs, because a float such as 3 * 19.9 is stored as 59.699999999999996.

example-2.py · A receipt line
item = "Travel Yoga Mat"
qty = 3
price = 19.9
print(f"{qty} x {item} at {price:.2f} each")
print(f"Line total: {qty * price}")
print(f"Line total: {qty * price:.2f}")

Widths make columns line up. {city:<12} pads the text to 12 characters, aligned left. {high:>6.1f} makes a 6-character column, aligned right, with one decimal. Headings can be padded too: put the heading text in quotes inside the braces.

example-3.py · A weather table that lines up
print(f"{'City':<12}{'High':>6}{'Low':>6}")
city = "Great Falls"
high = 6.7
low = -5.5
print(f"{city:<12}{high:>6.1f}{low:>6.1f}")
city = "Miami"
high = 27
low = 19.4
print(f"{city:<12}{high:>6.1f}{low:>6.1f}")

When to use it: whenever output mixes words and values. Use :.2f for money, :<n and :>n for columns, and :, for thousands separators (f"{1500000:,}" is 1,500,000). Mistakes to avoid:

  • Forgetting the f. The braces are then printed as ordinary characters.
  • Using a number spec such as .2f on text, which raises ValueError.
Review
  • + can't join text and a number. An f-string puts any value or expression into text with braces.
  • A spec after a colon controls the look: .2f for two decimals, <n and >n for columns, , for thousands.
  • A spec only changes how a value is shown, not the value itself.
  • Next: characters beyond A to Z, and the numbers behind every character.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Fill a sentence with values — Strings & Text · Runtime