Python lesson 15

String Formatting

Build polished messages by embedding variables directly inside strings!

f-Strings. The Modern Way

An f-string starts with the letter f before the opening quote: f"...". Inside the string you put variable names (or expressions) inside curly braces {}. Python replaces them with their values at runtime. You can also control formatting: {price:.2f} formats a float to 2 decimal places. F-strings are cleaner than joining strings with +.

name = "Alex"
age = 14
print(f"Hello, {name}! You are {age} years old.")

name = "Alex"
age = 14
print(f"Hello, {name}! You are {age} years old.")

What Goes In The Braces?

name = "Ada"
score = 42
print(f"{name} scored {score}")

Greeting Card

Click Run to see an f-string that combines a name and a number into one clean sentence.

Hint: Click Run! Change player and score, then run again. F-strings update automatically. No + signs needed.

player = "Sam"
score = 1450
print(f"Player: {player}")
print(f"Score: {score}")
print(f"Well done, {player}! You earned {score} points.")

Price Tag

Format a price to exactly two decimal places using :.2f inside the curly braces. Run to see the tidy output!

Hint: :.2f means "format as a float with 2 decimal places". Try price = 9.9 or price = 100. the output always shows cents.

item = "Headphones"
price = 34.5
print(f"{item}: ${price:.2f}")
print(f"With 10% discount: ${price * 0.9:.2f}")

Name Tag Generator

Build a formatted name tag using f-strings. Change the details and run to generate a new tag!

Hint: Try changing first, last, grade, and school. You can put any expression inside {}: even f"{grade + 1}" works!

first = "Jordan"
last = "Lee"
grade = 8
school = "CodeIt Academy"
print(f"Name:   {first} {last}")
print(f"Grade:  {grade}")
print(f"School: {school}")

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.