The format-spec toolbox
Change the width, the fill character or the digits and watch the line change.
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.
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.
With done = 7 and total = 8, print 7/8 = 87.5%.
With x = 5, print x = 5, x ** 2 = 25 using the = specifier, without typing the names yourself.
Explain it without notes
What does f"{x:>10.2f}" do, part by part?
How do = and !r help when debugging?
Why is it dangerous to call .format on a template that comes from a user?
When would you still choose str.format or % over an f-string?
Expected output
[Asha ] [ Asha] [ Asha ] [**Asha**]
price: 1,234.50
price: [ 1234.5]
ratio: 25.6%
count: 00042 +42 101010 2a 0x2a 52
big: 1,234,567,890 1_234_567_890
sci: 1.235e+05
'Asha' vs Asha
count = 42
count * 2 = 84
[ 3.142]