Python f-strings · Clean & Powerful String Formatting

Mingming Li — Click any blue heading below to expand the content.

What are f-strings? They let you put variables directly inside strings using curly braces { }. Just add an f before the quotes!

Table of Contents

1. What are f-strings?

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"
Key idea: f-strings let you put Python code directly inside strings. Everything inside { } is evaluated as Python code and converted to a string.

2. Why use f-strings? (Comparison)

MethodSyntaxReadability
f-strings (best)f"Hello {name}"Excellent - variables inside string
.format() method"Hello {}".format(name)OK - variable separate
% formatting (old)"Hello %s" % namePoor - hard to read
String concatenation"Hello " + namePoor - 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)
Recommendation: Always use f-strings for new code. They are faster, cleaner, and the modern Python standard.

3. Basic variable insertion

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

4. Expressions inside f-strings

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")
You can do math, call functions, access lists/dictionaries, and even use conditionals inside { }!

5. Number formatting

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
Format specifiers: .2f = 2 decimal places, % = percentage, , = thousands separator, :>5 = right align width 5.

6. String formatting

# 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}

7. Multiline f-strings

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)

8. Quick reference

# 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 }

9. Quick Challenge: Find the f-string in Our Game

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:

  1. Where is the f-string in this code?
  2. What variable is being inserted?
  3. How would you format the score to show as "Score: 042" (with leading zero)?
  4. How would you show the score with commas (e.g., "Score: 1,234")?
Click for answers
  1. f"Score: {score}"
  2. The variable score
  3. f"Score: {score:03d}" (3 digits with leading zeros)
  4. f"Score: {score:,}"

10. Exercises

Try these exercises to practice f-strings. Write your code in Thonny.

  • Exercise 1: Print "My name is Alice and I am 25 years old" using name = "Alice" and age = 25.
  • Exercise 2: Calculate price = 19.99 * quantity = 3 inside an f-string: "Total: $59.97".
  • Exercise 3: Print "Hello, John Doe!" from first = "John" and last = "Doe".
  • Exercise 4: Print pi = 3.1415926535 with 2, 3, and 5 decimal places.
  • Exercise 5: Print score = 0.85 as "85%".
  • Exercise 6: Print "10 + 3 = 13" and "10 * 3 = 30" using a=10, b=3.
  • Exercise 7: Pad number = 42 to 5 digits with zeros → "00042".
  • Exercise 8: Center "Python" in width 20 with spaces.
  • Exercise 9: Print city = "New York" and population = 8419000 as "New York has 8,419,000 people".
  • Exercise 10: Use a ternary: print "Pass" if score >= 60 else "Fail".
  • Exercise 11: Create a receipt using a multiline f-string with items, prices, and total.
  • Exercise 12: Print the literal text "{variable}" (not the variable value).
  • Exercise 13: Print "Python" in reverse inside an f-string using slicing.
  • Exercise 14: From a list fruits = ["apple","banana","cherry"], print "I like apple, banana, cherry".
  • Exercise 15: From a dictionary student = {"name": "Alice", "grade": 92}, print "Alice scored 92%".

11. Common Errors & Solutions

  • Missing 'f' prefix
    -> "Hello {name}" prints literally. Fix: f"Hello {name}"
  • Quote mismatch
    -> f'It's {name}' breaks. Fix: use double quotes f"It's {name}"
  • Backslash in expression
    -> f"{\n}" is invalid. Fix: move backslash outside.
  • Nested f-strings
    -> f"Hello {f'inner'}" doesn't work. Fix: use one f-string.
  • Using f-strings in Python 3.5 or earlier
    -> f-strings require Python 3.6+. Upgrade Python!
Pro tip: The f must be immediately before the opening quote: f"text" not f "text"!

12. Check Your Understanding

  1. What letter do you put before a string to make it an f-string?
  2. What symbols do you use to embed variables inside an f-string?
  3. How do you format a number to 2 decimal places?
  4. How do you add a thousands separator to a number?
  5. How do you print literal curly braces in an f-string?
Click for Answers
  1. The letter f
  2. Curly braces { }
  3. {value:.2f}
  4. {value:,}
  5. Use double braces: {{ and }}

13. Your Progress Tracker

Check off each item as you master it:
I can create basic f-strings with variables
I understand f-strings are better than .format()
I can put expressions inside { }
I can format numbers (decimals, percentage, thousands)
I can align and pad text
I can create multiline f-strings
I completed at least 10 exercises
I can spot f-strings in our game code