F-strings (formatted string literals) let you embed variables and expressions directly in your text. They make your output clean and readable!
Add an f before the opening quote, then put variables in {curly braces}:
name = "Bob"
print(f"Hello, {name}!")Output: Hello, Bob!
Include as many variables as you need:
first_name = "Vidar"
last_name = "Smith"
age = 30
print(f"{first_name} {last_name} is {age} years old")Output: Vidar Smith is 30 years old
You can put calculations directly in the braces:
age = 25
print(f"Next year you'll be {age + 1}")
print(f"In 5 years you'll be {age + 5}")Output:
Next year you'll be 26
In 5 years you'll be 30name = "Vidar"
print(f"Hello, {name.upper()}!")Output: Hello, VIDAR!
Without f-strings (the old way):
name = "Vidar"
age = 22
print(name, "is", age, "years old") # Awkward spacingWith f-strings (clean and clear):
name = "Vidar"
age = 22
print(f"{name} is {age} years old")player = "Hero"
score = 1500
level = 5
print(f"Player: {player}")
print(f"Score: {score}")
print(f"Level: {level}")item = "Laptop"
price = 899.99
quantity = 1
tax_rate = 0.08
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
print(f"Item: {item}")
print(f"Price: {price}")
print(f"Tax: {tax}")
print(f"Total: {total}")celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is {fahrenheit}°F")Output: 25°C is 77.0°F
Create multi-line output:
name = "Vidar"
city = "Roskilde"
country = "Denmark"
print(f"Name: {name}")
print(f"City: {city}")
print(f"Country: {country}")Use different quotes to avoid conflicts:
# use double quotes for f-string, single inside
message = f"She said, 'Hello!'"
# or vice versa
message = f'He said, "Goodbye!"'Labeling output:
score = 95
print(f"Score: {score}")Creating sentences:
name = "Bob"
job = "developer"
print(f"{name} is a {job}")Showing calculations:
width = 10
height = 5
print(f"Area: {width * height}")f before the quote{}Ready to work with text? Learn about String Methods to manipulate and transform text!