LESSON 05
Modern String Formatting
Stop gluing text together by hand. Write the sentence once and let Python fill in the blanks.
USES: print( ), variables, strings, + and the comma, maths, len( ) and methods.
01
The problem
Last lesson you met two ways to mix text and numbers, and both have a weakness. Gluing with + crashes as soon as a number is involved. The comma works, but it is hard to read, you can't control the spaces, and it can't be stored as one string. Gluing sentences from pieces is slow and easy to get wrong. Python has a cleaner way.
02
The f-string
Put the letter f right before the opening quote. Then write your variables inside curly braces { }. The f tells Python this string has blanks to fill, and Python swaps each { } for what is in the box. The number needed no conversion, and the spaces are exactly where you typed them.
BLUEPRINT ยท TAP OR HOVER EACH PIECE
Blueprint 1 of 1: the f-string. Tap each piece.
03
Forgetting the f
This is the most common mistake. Without the f, the braces are ordinary characters and Python shows them as they are. Compare the two lines below.
04
Maths inside the braces
The braces can hold more than a variable name. They can hold a calculation, and Python works it out first. You can also use the tools from Lesson 4, like methods and len( ). The braces act as a small workspace: Python works out whatever is inside, then drops the answer into the sentence.
05
Controlling decimals
Python shows 4.5 as 4.5, but nobody writes a price that way. To set the number of decimals, add :.2f inside the braces, after the name. Reading it: the : means 'format this', .2 means '2 digits after the decimal point', and f means 'as a decimal number'. The number is rounded only when shown. The variable itself does not change.
06
Errors in f-strings
Misspell a variable name inside the braces and Python stops with a NameError. This is normal, and it is useful: the message tells you exactly what Python could not find. Here it says there is no box called nme, so the fix is to check the spelling.
07
Bonus: new lines
A \n inside a string starts a new line. A backslash followed by n counts as one special character, not two. A \t adds a wide gap, called a tab, in the same way. Both work inside f-strings too.
08
Quick quiz: what does this print?
What does print(f"{2 + 3}") show? Decide first, then check.
09
Quick quiz: what is missing?
This code prints Hello {name} instead of Hello Ada. What fixes it?