Mingming Li — Click any blue heading below to expand the content.
{ }. Just add an f before the quotes!
f-strings (formatted string literals) are the easiest way to embed variables inside Python strings. Put an f before the opening quote and use { } around variables.
# Basic f-string syntax
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
# Why "f"? f stands for "format" or "fast"
# The f tells Python: "This string has expressions inside curly braces"
{ } is evaluated as Python code and converted to a string.
| Method | Syntax | Readability |
|---|---|---|
| f-strings (best) | f"Hello {name}" | Excellent - variables inside string |
| .format() method | "Hello {}".format(name) | OK - variable separate |
| % formatting (old) | "Hello %s" % name | Poor - hard to read |
| String concatenation | "Hello " + name | Poor - messy with many vars |
# Same example with different methods
name = "Alice"
age = 25
city = "New York"
# f-string (BEST - Python 3.6+)
print(f"{name} is {age} years old and lives in {city}")
# .format() method (older)
print("{} is {} years old and lives in {}".format(name, age, city))
# String concatenation (messy)
print(name + " is " + str(age) + " years old and lives in " + city)
# Inserting variables of different types
name = "Bob"
age = 30
height = 1.85
is_student = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}")
print(f"Student: {is_student}")
# Multiple variables in one string
print(f"{name} is {age} years old, {height}m tall. Student: {is_student}")
You can put any valid Python expression inside the curly braces — not just variable names!
# Arithmetic operations
a = 10
b = 3
print(f"{a} + {b} = {a + b}")
print(f"{a} * {b} = {a * b}")
# Method calls
name = "alice"
print(f"Capitalized: {name.capitalize()}")
print(f"Uppercase: {name.upper()}")
# List and dictionary access
fruits = ["apple", "banana", "cherry"]
print(f"First fruit: {fruits[0]}")
person = {"name": "Alice", "age": 25}
print(f"{person['name']} is {person['age']} years old")
# Conditional expressions (ternary)
score = 85
print(f"You {'passed' if score >= 60 else 'failed'} the exam")
{ }!
pi = 3.14159265359
price = 24.5
percentage = 0.875
big_number = 1234567
# Decimal places
print(f"pi to 2 decimals: {pi:.2f}") # 3.14
print(f"Price: ${price:.2f}") # $24.50
# Percentage
print(f"Score: {percentage:.1%}") # 87.5%
# Thousands separator
print(f"Big number: {big_number:,}") # 1,234,567
# Padding and alignment
num = 42
print(f"Right aligned: {num:>5}") # " 42"
print(f"Zero padding: {num:05d}") # "00042"
# Hex and binary
print(f"Hex: {255:x}") # ff
print(f"Binary: {10:b}") # 1010
.2f = 2 decimal places, % = percentage, , = thousands separator, :>5 = right align width 5.
# String alignment
word = "Python"
print(f"|{word:10}|") # |Python |
print(f"|{word:>10}|") # | Python|
print(f"|{word:^10}|") # | Python |
# Truncation
long_word = "HelloWorld"
print(f"{long_word:.5}") # Hello (truncate to 5 chars)
# Escape curly braces (use double braces)
print(f"{{curly braces}}") # {curly braces}
print(f"{{{name}}}") # {Alice}
name = "Alice"
age = 25
city = "New York"
# Using triple quotes
message = f"""
Name: {name}
Age: {age}
City: {city}
"""
print(message)
# Using parentheses to break lines
long_message = (
f"Hello {name}, "
f"you are {age} years old. "
f"We hope you enjoy your stay in {city}!"
)
print(long_message)
# BASIC SYNTAX
f"text {variable} more text"
# NUMBERS
f"{value:.2f}" # 2 decimal places
f"{value:.0%}" # percentage
f"{value:,}" # thousands separator
f"{value:>10}" # right align (width 10)
f"{value:<10}" # left align
f"{value:^10}" # center
f"{value:05d}" # zero pad to width 5
# STRINGS
f"{text:10}" # left align width 10
f"{text:>10}" # right align
f"{text:^10}" # center
f"{text:.5}" # truncate to 5 chars
# EXPRESSIONS
f"{a + b}" # arithmetic
f"{func(x)}" # function call
f"{list[0]}" # list access
f"{dict['key']}" # dict access
# ESCAPE BRACES
f"{{" # prints {
f"}}" # prints }
Look at this code from our game's game over screen:
# Game over screen
font = pygame.font.Font(None, 36)
text = font.render("Press SPACE to start", True, (100, 100, 255))
screen.blit(text, text_rect)
# If we had a score display
score = 42
score_text = f"Score: {score}" # <-- f-string!
font = pygame.font.Font(None, 48)
text_surface = font.render(score_text, True, (255, 255, 255))
Questions:
f"Score: {score}"scoref"Score: {score:03d}" (3 digits with leading zeros)f"Score: {score:,}"Try these exercises to practice f-strings. Write your code in Thonny.
name = "Alice" and age = 25.price = 19.99 * quantity = 3 inside an f-string: "Total: $59.97".first = "John" and last = "Doe".pi = 3.1415926535 with 2, 3, and 5 decimal places.score = 0.85 as "85%".a=10, b=3.number = 42 to 5 digits with zeros → "00042".city = "New York" and population = 8419000 as "New York has 8,419,000 people".score >= 60 else "Fail".fruits = ["apple","banana","cherry"], print "I like apple, banana, cherry".student = {"name": "Alice", "grade": 92}, print "Alice scored 92%"."Hello {name}" prints literally. Fix: f"Hello {name}"f'It's {name}' breaks. Fix: use double quotes f"It's {name}"f"{\n}" is invalid. Fix: move backslash outside.f"Hello {f'inner'}" doesn't work. Fix: use one f-string.f must be immediately before the opening quote: f"text" not f "text"!
f{ }{value:.2f}{value:,}{{ and }}