Python fundamentals
Strings and formatted output
Write strings with quotes and place variable values into messages using f-strings.
Lesson 10 of 63
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
A string is text enclosed in matching single or double quotes. You can put variable values into a message with an f-string: write f immediately before the opening quote and put each variable name inside braces.
name = "Sam"
sessions = 3
print(f"{name} planned {sessions} sessions.")Sam planned 3 sessions.
Join text carefully
The + operator joins strings. It does not automatically turn an int into text. An f-string converts displayed values to text for the message.
first = "Python"
second = "practice"
print(first + " " + second)
minutes = 25
print(f"Each session is {minutes} minutes.")Python practice Each session is 25 minutes.
Why this works
An f-string evaluates expressions inside braces when that line runs. If a variable changes, a later f-string uses its new value. The f prefix must be immediately before the opening quote; without it, braces remain literal text.
Practice
Make name, sessions, and minutes_per_session variables. Print a complete sentence using one f-string. Change a value and rerun the script to see the sentence update.
Why does f"{sessions} sessions" work when sessions is an int?
Reveal answer
The f-string formats the integer as text inside the message.
Try another case
If name = "Ava" and minutes = 20, what does print(f"{name}: {minutes} min") display?
Check your answer
Reveal answer
It displays Ava: 20 min.
Your progress
Reveal the check answer or reach the end to complete this lesson.