String Formatting
Build readable text that includes variables and formatted numbers.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
An f-string places a value inside a string when you write an f before the opening quote. Curly braces mark each expression to evaluate. This is useful for labels, messages, and summaries.
A format specifier inside the braces can control display. For example, :.2f shows a floating-point value with two digits after the decimal point.
- Prefix a string with f
- Use {expression} placeholders
- Format decimals with :.2f
See it step by step
Read the code, predict the output, then compare it with the result.
01. Insert two values
student = "Ava"
topic = "lists"
print(f"{student} is studying {topic}.")Ava is studying lists.The f before the string tells Python to replace each {name} with its current value.
02. Format a decimal
score = 7.5
print(f"Score: {score:.2f}")
print(f"Next lesson: {2 + 1}")Score: 7.50
Next lesson: 3The :.2f format displays two decimal places; an f-string can also evaluate an expression.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Set topic = 'loops'. In an f-string, put {student} and {topic} inside braces, and include the exact punctuation at the end.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Missing f prefix
name = "Maya"
print("Hi, {name}")name = "Maya"
print(f"Hi, {name}")What happens: The literal text Hi, {name} is displayed.
Add f before the opening quote to evaluate placeholders.
Unknown placeholder
name = "Maya"
print(f"Hi, {username}")name = "Maya"
print(f"Hi, {name}")What happens: NameError because username has not been defined.
A placeholder must refer to a defined name or valid expression.