Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.3 — Formatting Text: f-strings in Depth
Python · Example 3 of 4

A neat table

Strings are left-aligned by default and numbers right-aligned, so a table lines up almost for free.

An f-string is a string with {} holes that Python fills with values, and a small format-spec language after a colon controls width, alignment, number style, percentages and dates. This topic covers the whole language, plus the older str.format and % styles you will meet in other people's code.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the item name Tea left-aligned in 8 characters and the price 1234.5 right-aligned in 12 characters with a thousands separator and two decimals.

02

With done = 7 and total = 8, print 7/8 = 87.5%.

03

With x = 5, print x = 5, x ** 2 = 25 using the = specifier, without typing the names yourself.

Explain it without notes

01

What does f"{x:>10.2f}" do, part by part?

02

How do = and !r help when debugging?

03

Why is it dangerous to call .format on a template that comes from a user?

04

When would you still choose str.format or % over an f-string?

A neat table
Sign in to run this example in your browser.

Expected output

Item        Qty     Price
-------------------------
Pen           3     12.50
Notebook     12  1,250.00
Bag           1    999.99