Introduction
F-strings help you put values inside text easily and clearly. They make your messages or results look nice and readable.
Jump into concepts and practice - no test required
F-strings help you put values inside text easily and clearly. They make your messages or results look nice and readable.
f"text {variable} more text {expression}"{} to include their values.name inside the text.name = "Anna" print(f"Hello, {name}!")
age = 25 print(f"You are {age} years old.")
x = 5 y = 3 print(f"Sum is {x + y}.")
price = 9.99 print(f"Price: ${price:.2f}")
This program shows how to use f-strings to print variables and expressions in sentences.
name = "Sam" age = 30 height = 1.75 print(f"Name: {name}") print(f"Age: {age} years") print(f"Height: {height} meters") print(f"Next year, {name} will be {age + 1} years old.")
You can put any expression inside the braces, like math or function calls.
F-strings work only in Python 3.6 and later versions.
Use :.2f inside braces to format floats with 2 decimals.
F-strings make it easy to mix text and values in one string.
Use curly braces {} to insert variables or expressions.
They help create clear and readable output messages.
f-strings in Python?{}.name into a string?f before the quotes and uses curly braces {} to insert variables.f"Hello, {name}!". Options A and B lack the f prefix, and C uses incorrect syntax with $name.name = "Alice"
age = 30
print(f"{name} is {age} years old.")name and age are replaced by their values "Alice" and 30 inside the string.age = 25
print(f"Age is {age"){ but no matching closing brace }, causing a syntax error.age is defined, and quotes are correct.price = 9.8765 # Choose the correct print statement
:.2f inside the curly braces.{price:.2f} correctly. print(f"Price: ${price:2f}") misses the dot, print(f"Price: ${price:.2}") misses the type specifier, and print(f"Price: ${price:.2d}") uses invalid d for decimals.