Learning LibraryCore Coding LibraryKids

f-strings: drop values right into your words

Printing words and numbers with commas works, but the spaces can come out wrong. An f-string lets you write the sentence exactly as you want it, with gaps for the values.

The big idea

Put an f before the quotes, and anything inside curly brackets {} is swapped for its value.

See it in code

1Start simple

The f goes right before the opening quote. Inside the string, {total} is a gap that Python fills with the variable's value:

python
total = 7
print("Total: $", total)
print(f"Total: ${total}")
The same total, printed two ways:
Total: $ 7
Total: $7

The comma version put a space after the dollar sign. The f-string put the number exactly where the curly brackets were.

2A step further

One f-string can have many gaps. Each pair of curly brackets holds one variable:

python
bake = "Brownies"
how_many = 3
print(f"You ordered {how_many} {bake}")
Two values in one sentence:
You ordered 3 Brownies

Read the line out loud, saying the values where the brackets are. If it sounds right, it will print right.

3In the bakery

Curly brackets can hold math, too. Every line of this receipt is an f-string:

python
shop_name = "ELECTRIC BAKERY"
bake = "Brownies"
how_many = 3
price_each = 2
tip = 1

print(f"*~* {shop_name} RECEIPT *~*")
print(f"You ordered {how_many} {bake}")
print(f"Subtotal: ${how_many * price_each}")
print(f"Tip: ${tip}")
print(f"Total: ${how_many * price_each + tip}")
A tidy receipt:
*~* ELECTRIC BAKERY RECEIPT *~*
You ordered 3 Brownies
Subtotal: $6
Tip: $1
Total: $7

Python works out how_many * price_each first, then drops the answer into the sentence. The $ is just an ordinary character sitting next to the gap.

The same idea, everywhere

Anywhere a program shows a changing value in a sentence, an f-string is doing the work. A game's score. A menu line. A message with today's special in it.

Try it yourself

Change how_many to 5 and run it. Three lines of the receipt update by themselves. Then add a line that prints "Thanks for visiting the {shop_name}!" as an f-string.

The common mistake

Forgetting the f. Without it, print("Total: ${total}") shows the curly brackets and the word total, exactly as typed. The f is what switches the brackets on.

What it unlocks

f-strings get even better with text tools like .title() and .upper(). They also make clear output for a for loop that prints a whole menu.

Older, or want more depth? Read the Teens version →