Python Tutorials

Choose a lesson to begin

F-Strings and Formatting

F-strings (formatted string literals) let you embed variables and expressions directly in your text. They make your output clean and readable!

Basic F-Strings

Add an f before the opening quote, then put variables in {curly braces}:

name = "Bob"
print(f"Hello, {name}!")

Output: Hello, Bob!

Multiple Variables

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

Expressions in F-Strings

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 30

String Methods in F-Strings

name = "Vidar"
print(f"Hello, {name.upper()}!")

Output: Hello, VIDAR!

Why F-Strings?

Without f-strings (the old way):

name = "Vidar"
age = 22
print(name, "is", age, "years old")  # Awkward spacing

With f-strings (clean and clear):

name = "Vidar"
age = 22
print(f"{name} is {age} years old")

Real-World Examples

Game Score Display

player = "Hero"
score = 1500
level = 5
print(f"Player: {player}")
print(f"Score: {score}")
print(f"Level: {level}")

Shopping Receipt

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}")

Temperature Conversion

celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is {fahrenheit}°F")

Output: 25°C is 77.0°F

Multiple Lines

Create multi-line output:

name = "Vidar"
city = "Roskilde"
country = "Denmark"
print(f"Name: {name}")
print(f"City: {city}")
print(f"Country: {country}")

F-String Quotes

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!"'

Common Patterns

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}")

Try It Out!

  • Create variables for a person (name, age, city) and print a bio using f-strings
  • Make a simple calculator that shows: "10 + 5 = 15"
  • Create a movie ticket receipt (movie name, price, quantity, total)
  • Print your height in both feet and inches: "I am 5 feet 9 inches tall"
  • Pro Tips

    Next Steps

    Ready to work with text? Learn about String Methods to manipulate and transform text!

    🐍 Python Runner