Lesson 7 of 10
In lesson 1.5 you saw that combining text and numbers requires converting the number with
str() first:
age = 25
print("I am " + str(age) + " years old")
That works, but it gets clunky fast with more variables. Python has a much cleaner tool for this: f-strings.
What is an f-string?
An f-string is a string literal prefixed with f, where anything inside { } is evaluated as
Python code and inserted directly — no manual str() conversion needed.
age = 25
print(f"I am {age} years old")
You can put any expression inside the braces, not just a variable:
price = 19.99
quantity = 3
print(f"Total: {price * quantity}")
Multiple values in one f-string
name = "Ada"
age = 28
print(f"{name} is {age} years old")
Formatting numbers
You can control how a number is displayed by adding a format spec after a colon inside the braces. A common one is rounding decimals:
price = 19.9999
print(f"Price: ${price:.2f}")
.2f means "format as a fixed-point decimal with 2 digits after the point."
Try it yourself
Given a name and a score, print a sentence using an f-string in the form:
"<name> scored <score> points".
Checkpoint
- f-strings start with
f"..."and let you embed expressions in{ }. - No manual
str()conversion needed inside an f-string. {value:.2f}formats a number to 2 decimal places.
Questions about this lesson
Log in to ask a question.