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.

INPUTname = "Ada" age = 20 print("Hi", name + ",", "you are", age)
OUTPUTHi Ada, you are 20
CRASHESprint("Hi " + name + ", you are " + age) # TypeError
WORKSprint(f"Hi {name}, you are {age}") # Hi Ada, you are 20

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.

INPUTname = "Ada" age = 20 print(f"Hi {name}, you are {age}")
OUTPUTHi Ada, you are 20
TIPOld tutorials also teach "Hi {}".format(name). They still work, but the blank and its value sit far apart, which makes them harder to read. In an f-string the blank and its value are in the same place.
METAPHORAn f-string is a form letter: "Dear {name}, your order of {item} has shipped." You write it once, and the blanks fill in with each person's details. Where it stops working: in a real form letter, someone else fills in the blanks. Here Python reads the current value from the variable.
OLD HABIT"Hi %s" % name # old tutorials
MODERNf"Hi {name}" # modern

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.

INPUTname = "Ada" print("Hi {name}") print(f"Hi {name}")
OUTPUTHi {name} Hi Ada
TIPIf you ever see curly braces in your output, you forgot the f.

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.

INPUTname = "ada" age = 20 print(f"Next year you will be {age + 1}") print(f"{age} times 2 is {age * 2}") print(f"{name.upper()} has {len(name)} letters")
OUTPUTNext year you will be 21 20 times 2 is 40 ADA has 3 letters
TIPKeep the braces short. If the calculation is long, work it out first, store it in a variable, and put the variable in the braces. That is easier to read.

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.

INPUTprice = 4.5 print(f"Price: {price}") print(f"Price: {price:.2f}") print(f"One third: {10 / 3:.2f}")
OUTPUTPrice: 4.5 Price: 4.50 One third: 3.33
TIPYou don't need to memorize the other options. :.2f covers money, averages and most everyday cases.

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.

INPUTname = "Ada" print(f"Hi {nme}")
OUTPUTNameError: name 'nme' is not defined

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.

INPUTname = "Ada" age = 20 print(f"Name: {name}\nAge: {age}") print(f"Name:\t{name}")
OUTPUTName: Ada Age: 20 Name: Ada
TIPThis step is a bonus. You can skip it without missing anything in the lessons that follow.

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?

Report a mistake or suggest a lesson