small steps

Format text and numbers with Python f-strings

Put values into text, round and line up numbers, and debug faster with f-strings, by printing a small café bill one step at a time.

BasicsBy Noufal12 min readPublished Tested on Python 3.15
Part 3 of 4 in Python basics
6 steps in this tutorial
  1. See the problem
  2. Put values inside braces
  3. Format numbers
  4. Line things up
  5. Debug with an equals sign
  6. Avoid the two common mistakes

What you'll learn

  • Put variables and calculations inside text
  • Round, group and line up numbers in neat columns
  • Debug faster by printing a name and its value together
  • Spot the two f-string mistakes beginners make most

Before you start

You want Python to print a line like Coffee x 2 = 7.00, but joining text and numbers keeps going wrong. f-strings fix that, and they also round, group and line up numbers. In six small steps, you'll build a café bill that looks like a real one.

Step 1: See the problem

You run a small café, and you want Python to print one line of a bill: the item, how many, and what they cost. Here's what most people try first:

bill.py
item = "Coffee"
qty = 2
price = 3.5

print(item + " x " + qty + " = " + qty * price)

Run it, and Python stops with an error:

Output (your file path will be longer)
Traceback (most recent call last):
  File "bill.py", line 5, in <module>
    print(item + " x " + qty + " = " + qty * price)
          ~~~~~~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

Read the last line first: it's the one that says what went wrong. "Concatenate" means join, and str is Python's name for text. So Python can only join text to text, and qty is a number (an int).

Why doesn't Python turn the number into text for you? Because + does two jobs: it adds numbers and joins text. "2" + 2 could mean 4 or "22", and Python won't guess. It stops and tells you.

Try it

Open the Python shell (type python in a terminal, or python3 on macOS and Linux) and enter "2" + 2. Then try "2" + str(2) and 2 + int("2"). Which one gives 4?

The usual workaround is to wrap every number in str():

Python
print(item + " x " + str(qty) + " = " + str(qty * price))
Coffee x 2 = 7.0

It works, but str() is everywhere, and the price shows 7.0 where a bill should say 7.00. You could also write print(item, "x", qty, "=", qty * price). Commas are fine for quick output, but Python picks the spaces, and you get no text back to keep or send.

Now you know why joining text and numbers with + breaks. In Step 2, one letter fixes this same line.

Step 2: Put values inside braces

Here's the same line as an f-string. Put an f before the opening quote, and write each value inside curly braces, {}, right where it belongs in the text:

bill.py
item = "Coffee"
qty = 2
price = 3.5

print(f"{item} x {qty} = {qty * price}")
Coffee x 2 = 7.0

No + and no str(), and the code reads almost like the output. The f stands for "formatted". It tells Python to work out what's inside each pair of braces and put the result into the text, converted for you.

The braces take more than names. Anything that gives a value works there: a calculation like {qty * price}, or a method call like {item.upper()}:

Python
print(f"{item.upper()} x {qty} = {qty * price}")
COFFEE x 2 = 7.0

Try it

Add a 10% service charge inside the braces: {qty * price * 1.1}. What does Python print? (Step 3 tidies it up.)

Once Python has built it, an f-string is ordinary text (a str). So you can keep it in a variable, and print it, save it or send it later:

Python
line = f"{item} x {qty} = {qty * price}"
print(line)
Coffee x 2 = 7.0

The Python tutorial has more on formatted string literals (opens in a new tab) if you want to read ahead.

Now you can put any value into text with one letter and a pair of braces. But the bill still says 7.0 where it should say 7.00. Step 3 fixes that.

Step 3: Format numbers

To control how a value looks, put a colon after it inside the braces, then a format. Start with the bill's real problem, the decimal places:

Python
print(f"{item} x {qty} = {qty * price:.2f}")
Coffee x 2 = 7.00

Read :.2f as "two digits after the point (.2), as a plain decimal number (f)". It rounds as well, so the service charge from Step 2, {qty * price * 1.1:.2f}, prints 7.70 instead of 7.700000000000001.

A comma groups big numbers in thousands. A café order never gets that big, but a month of sales does:

Python
sales = 12840.5
print(f"This month: {sales:,}")
print(f"This month: {sales:,.2f}")
This month: 12,840.5
This month: 12,840.50

The second line combines both: the comma first, then .2f. The order matters: {sales:.2f,} stops with ValueError: Invalid format specifier. The comma always groups in threes, so Indian-style grouping like 1,50,000 isn't built in.

A percent sign multiplies by 100 and adds the %. Here .0 means no decimal places:

Python
charge = 0.1
print(f"Service charge ({charge:.0%})")
Service charge (10%)

Watch out

Two friends split a 5.35 sandwich. Each half is 5.35 / 2, which is 2.675, and you'd expect :.2f to round it up to 2.68:

Python
print(f"{5.35 / 2:.2f}")
print(f"{5.35 / 2:.20f}")
2.67
2.67499999999999982236

Each friend pays 2.67, so the café gets 5.34, a cent short. Showing 20 digits reveals why: a float stores a close approximation of the number, and formatting rounds what's stored. That's fine for printing. For real money, use Python's decimal module (opens in a new tab) (a later tutorial).

These formats are part of a small language of their own, the format specification mini-language (opens in a new tab), if you want the full list.

Now the bill shows numbers the way a bill should: 7.00, 12,840.50 and 10%. Next, line the items up in columns.

Step 4: Line things up

A bill is a table: names on the left, numbers on the right, and every row the same width. A format can set a width, and the side to line up on. The square brackets here show where the spaces go:

Python
item = "Coffee"
print(f"[{item:<10}]")
print(f"[{item:>10}]")
print(f"[{item:^10}]")
[Coffee    ]
[    Coffee]
[  Coffee  ]

10 is the width: Python pads the value with spaces to fill 10 characters. < lines it up on the left, > on the right and ^ in the centre. Leave the sign out and Python chooses: text goes left, numbers go right.

Widths combine with the number formats from Step 3. Put the width before the dot: {line_total:>10.2f} means 10 characters wide, lined up on the right, with 2 decimal places.

To fill with something other than spaces, put that character before the sign. That gives the bill a title:

Python
print(f"{' Bill ':=^30}")
============ Bill ============

The braces hold a plain string here: the word Bill with a space on each side, in single quotes because the f-string uses double ones. Step 6 shows why that matters.

Now the whole bill. The order is a list of tuples, one per item: name, quantity and price. The line for item, qty, price in order: takes each tuple apart into three variables (this is called unpacking).

bill.py
order = [
    ("Coffee", 2, 3.5),
    ("Sandwich", 1, 5.35),
    ("Chocolate cake", 1, 4.25),
]
charge = 0.1

print(f"{' Bill ':=^30}")
subtotal = 0
for item, qty, price in order:
    line_total = qty * price
    subtotal += line_total
    print(f"{item:<16}{qty:>4}{line_total:>10.2f}")
print("-" * 30)

service = subtotal * charge
label = f"Service ({charge:.0%})"
print(f"{'Subtotal':<20}{subtotal:>10.2f}")
print(f"{label:<20}{service:>10.2f}")
print(f"{'Total':<20}{subtotal + service:>10.2f}")
============ Bill ============
Coffee             2      7.00
Sandwich           1      5.35
Chocolate cake     1      4.25
------------------------------
Subtotal                 16.60
Service (10%)             1.66
Total                    18.26

The widths add up: 16 + 4 + 10 is 30 on the item rows, and 20 + 10 is 30 on the totals, so every line ends in the same column. The service label is built first as its own f-string (an f-string is ordinary text, remember), then lined up like any other text.

Try it

Make the name column narrower than the longest name: change <16 to <6 and run it again. What happens to the rows?

A width is a minimum. Python never cuts text short, so a longer value pushes the rest of its row along. Make each width fit the longest value you expect.

Now you have a finished bill, lined up in columns, from one loop and a few formats. When a number on it looks wrong, Step 5 shows the quickest way to check it.

Step 5: Debug with an equals sign

Say someone tidies the code and moves subtotal = 0 inside the loop. The bill still runs, but the subtotal is wrong:

Output (the subtotal line)
Subtotal                  4.25

That's the price of the cake alone. To see what's going on, add one line inside the loop, with an equals sign after each name:

Python
for item, qty, price in order:
    subtotal = 0
    line_total = qty * price
    subtotal += line_total
    print(f"{item=} {subtotal=}")
    print(f"{item:<16}{qty:>4}{line_total:>10.2f}")
Output (the debug lines)
item='Coffee' subtotal=7.0
item='Sandwich' subtotal=5.35
item='Chocolate cake' subtotal=4.25

{subtotal=} prints the name, an equals sign and the value, so you don't have to type the name twice. Now the bug is plain: the subtotal starts again from zero on every row. Move subtotal = 0 back above the loop. Then delete the debug line, so it doesn't end up on a customer's bill.

A few details worth knowing

Python
item = "Coffee "  # note the space at the end
subtotal = 16.6
charge = 0.1

print(f"{item=}")
print(f"{subtotal * charge=}")
print(f"{subtotal * charge = }")
print(f"{subtotal * charge=:.2f}")
print(f"{item=:<10}|")
print(f"{item=!s}|")
print(f"{item=!r:<12}|")
item='Coffee '
subtotal * charge=1.6600000000000001
subtotal * charge = 1.6600000000000001
subtotal * charge=1.66
item=Coffee    |
item=Coffee |
item='Coffee '   |

The | at the end of the last three lines only marks where the text stops.

  • Text shows its quotes, so the stray space at the end of 'Coffee ' stands out. A plain {item} would hide it.
  • Any expression works, and Python echoes it as you wrote it, so you can check a calculation without a new variable.
  • Spaces around = are kept, which makes longer debug lines easier to read.
  • A format still works after the =, like :.2f here.
  • But a format drops the quotes from text, as in {item=:<10}.
  • !s and !r choose for you: !s drops the quotes on purpose, and !r keeps them even with a format.

For bugs that one print line can't catch, Python has a built-in debugger: put breakpoint() (opens in a new tab) on a line, and the program pauses there so you can look around. That's a tutorial of its own.

Now you can check any value, or any calculation, with one =. Step 6 covers the two f-string mistakes beginners make most.

Step 6: Avoid the two common mistakes

Two mistakes catch almost everyone who is new to f-strings, and neither looks wrong at first glance.

Mistake 1: forgetting the f

Python
print("{item} x {qty} = {qty * price:.2f}")
{item} x {qty} = {qty * price:.2f}

Without the f, it's an ordinary string, and braces are ordinary characters. Python prints them as they are, with no error, so the mistake can travel all the way onto a customer's bill. If your output shows braces, look for the missing f.

When you do want braces in an f-string, double them:

Python
print(f"Use {{item}} to show {item}")
Use {item} to show Coffee

Mistake 2: the same quotes inside the braces

In Step 4, the bill's title used single quotes inside a double-quoted f-string. Here it is with double quotes inside:

Python
print(f"{" Bill ":=^30}")

On Python 3.12 and newer, this prints the title. On Python 3.11 and older, it stops:

Output on Python 3.10 (the last line)
SyntaxError: f-string: expecting '}'

Older versions end the string at the next double quote, so they read f"{" as the whole f-string, with a { that never closes. Python 3.12 changed that (PEP 701 (opens in a new tab)).

Why care, if your Python is newer? Your code may run somewhere older: a server, a friend's laptop, or a tool that's still on 3.11. Use the other kind of quote inside the braces. It works on every version, and it's clearer to read.

Try it

This end of the bill has both mistakes. Fix it so it prints the total, and runs on Python 3.11 and older too:

Python
total = 18.26
print("Total: {total:.2f}")
print(f"{"Thank you!":^30}")

Now you can spot both mistakes: braces in the output mean a missing f, and a SyntaxError on an older Python means the quotes inside match the quotes outside.

Recap

  • f-strings put values and calculations straight into text.
  • A colon adds a format: decimals, grouping, percentages.
  • Width and alignment turn rows into neat columns.
  • = prints a name and its value for quick debugging.
  • Watch for a missing f and for quotes on older Python.

Check yourself

Four quick questions.

print("Total: " + 7.0) stops with a TypeError. Why?
Show the answer

+ joins text or adds numbers, and Python won't guess which you meant: Mixing a str and a float with + could mean either, so Python stops instead of guessing.

f"{5.35 / 2:.2f}" prints 2.67, not 2.68. Why?
Show the answer

The float stored for 2.675 is a little less than 2.675: Floats hold a close approximation (2.67499999…), and formatting rounds what's stored.

f"{'Chocolate cake':<6}|" uses a width of 6. What does it print?
Show the answer

Chocolate cake|: A width is a minimum: Python never cuts text short, so it pushes the | along.

f"{" Bill ":=^30}" works on Python 3.15 but fails on a server running 3.11. Why?
Show the answer

Before 3.12, the quotes inside the braces can't match the ones outside: Older versions end the string at the next double quote. Use ' Bill ' inside, and it works everywhere.