Lesson 12/48 ยท ๐Ÿ Your First Python
๐Ÿ Your First PythonLesson 12/48
Phase 1 ยท Your First Python15 min

F-Strings & String Formatting

The modern way to put values inside text, used in every real Python program

You already know how to print text and store values in variables. But what about combining them? Imagine wanting to print: "Hello, Alice! You are 30 years old."
You could do this with +, but there's a far better way: f-strings (formatted string literals).
The old way vs f-stringspython
name = "Alice"
age = 30

# Old way (messy)
print("Hello, " + name + "! You are " + str(age) + " years old.")

# Modern way, f-strings (clean)
print(f"Hello, {name}! You are {age} years old.")
Put an f right before the opening quote to make it an f-string. Then use {curly braces} anywhere inside to insert a variable or expression.
Expressions inside braces
The braces aren't limited to variable names, you can put any Python expression inside:
Expressions in f-stringspython
price = 49.99
qty = 3

print(f"Total: {price * qty}")        # Total: 149.97
print(f"2 + 2 = {2 + 2}")            # 2 + 2 = 4
print(f"Name: {'alice'.upper()}")    # Name: ALICE
๐Ÿค”Quick Check

What does f"The answer is {6 * 7}" produce?

Format specifiers, controlling how values look
Add a colon after the variable name to control formatting:
Common format specifierspython
pi = 3.14159265
price = 1234567.89
score = 0.875

print(f"Pi to 2dp: {pi:.2f}")           # Pi to 2dp: 3.14
print(f"Price: {price:,.2f}")           # Price: 1,234,567.89
print(f"Score: {score:.0%}")            # Score: 88%
print(f"{'left':<10}|{'right':>10}")    # left      |     right
The most useful specifier for beginners: :.2f rounds a float to 2 decimal places, perfect for money and scores.
๐Ÿค”Quick Check

Which produces the output "Price: ยฃ9.99"?

๐ŸŒIn the Real World...

When your pipeline prints "Deploying app-v2.3 to production...", that's an f-string. kubectl output, Ansible task names, Terraform plan summaries, all built with string formatting.

Practice Exercises

0/3 solved
Exercise 1 of 3easy
โฑ 00:00

Receipt Printer

Print a receipt line using an f-string.
Given: item = "Coffee", price = 3.5, qty = 2Expected output: Coffee x2, ยฃ7.00
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00

Grade Reporter

Given a student's score out of 100, print their result as a percentage with 1 decimal place.
Given: name = "Sam", score = 73, total = 100Expected output: Sam scored 73.0%
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00

Table Formatter

Print a formatted two-column table using field widths.
Expected output (exactly):`Item Price-----------Coffee ยฃ3.50Tea ยฃ2.00`
solution.py
3 / 3
Solve all 3 exercises to unlock completion