Skip to content

F-Strings

F-strings (formatted string literals) provide a concise way to embed expressions inside string literals. Introduced in Python 3.6 (2016), they use f prefix and curly braces for interpolation.

String formatting required verbose methods:

# Old % formatting
name = "Alice"
age = 25
message = "Hello, %s! You are %d years old." % (name, age)
# .format() method
message = "Hello, {}! You are {} years old.".format(name, age)
message = "Hello, {name}! You are {age} years old.".format(name=name, age=age)

F-strings provide clean, readable syntax:

# F-string
name = "Alice"
age = 25
message = f"Hello, {name}! You are {age} years old."
# Expressions
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}"
# Method calls
text = "python"
formatted = f"Language: {text.upper()}"
# Formatting specifiers
price = 19.99
formatted_price = f"Price: ${price:.2f}" # "Price: $19.99"
# Multi-line f-strings
user = {"name": "Bob", "role": "admin"}
info = f"""
User Information:
Name: {user['name']}
Role: {user['role']}
"""
# Debug feature (Python 3.8+)
value = 42
debug = f"{value=}" # "value=42"
  • Readable: Expressions directly in string
  • Concise: Less verbose than .format()
  • Fast: Faster than other formatting methods
  • Powerful: Can include any Python expression
  • Debugging: = specifier shows variable name and value
  • Canโ€™t use backslashes inside {} (use temp variable)
  • Can nest f-strings (but readability suffers)
  • Raw f-strings: fr"..." or rf"..."
  • Evaluated at runtime, not compile time
  • Can format numbers, dates, custom objects
# Formatting numbers
value = 1234567.89
formatted = f"{value:,.2f}" # "1,234,567.89"
percent = f"{0.875:.1%}" # "87.5%"
# Date formatting
from datetime import datetime
now = datetime.now()
date_str = f"{now:%Y-%m-%d %H:%M:%S}"
# Custom alignment
name = "Alice"
aligned = f"|{name:<10}|" # left-aligned
aligned = f"|{name:>10}|" # right-aligned
aligned = f"|{name:^10}|" # centered
  1. Create an f-string that shows โ€œProduct: Laptop, Price: $999โ€

    Answer
    product = "Laptop"
    price = 999
    message = f"Product: {product}, Price: ${price}"
  2. Format ฯ€ (3.14159) to 2 decimal places

    Answer
    import math
    formatted = f"{math.pi:.2f}" # "3.14"
  3. Debug print a variable showing both name and value

    Answer
    count = 42
    print(f"{count=}") # Prints: count=42