Python
f-Strings
Master formatted string literals to embed expressions directly inside strings: the modern, readable way to build dynamic output in Python.
What Is an f-String?
An f-string (formatted string literal) is a string prefixed with f or F that lets you embed Python expressions directly inside curly braces {}. Python evaluates the expression and inserts the result into the string.
name = "Alice" age = 16 print(f"My name is {name} and I am {age} years old.")
Why f-Strings Matter
Anatomy of an f-String
The Core Rule
# Variables f"{name}" # Arithmetic f"Total: {price * qty}" # Method calls f"{name.upper()}" # Function calls f"Length: {len(items)}" # Ternary expression f"{'even' if n % 2 == 0 else 'odd'}"
Format Specifiers
After the expression, add a colon : followed by a format spec to control how the value is displayed.
pi = 3.14159265 print(f"Pi is approx {pi:.2f}") # Pi is approx 3.14 print(f"Pi is approx {pi:.4f}") # Pi is approx 3.1416 print(f"Score: {0.85:.1%}") # Score: 85.0% print(f"Count: {1000000:,}") # Count: 1,000,000
f-Strings vs Other Methods
| Method | Syntax | Readability |
|---|---|---|
| Concatenation | "Hi " + name | Low: messy with many vars |
| % formatting | "Hi %s" % name | Medium: C-style, dated |
| .format() | "Hi {}".format(name) | Medium: verbose |
| f-String | f"Hi {name}" | High: inline, clean |
How to Write an f-String
Example 1: Greeting
first = "Maya" last = "Chen" grade = 10 msg = f"Welcome, {first} {last}! You are in grade {grade}." print(msg)
Each {} is replaced by the value of the variable at that moment. No type conversion needed: the integer grade is automatically converted to its string representation.
Example 2: Expressions Inside Braces
items = ["apple", "banana", "cherry"] price = 4.5 qty = 3 print(f"Items: {len(items)}") print(f"Total: ${price * qty:.2f}") print(f"First: {items[0].upper()}")
You can call functions like len(), do arithmetic like price * qty, and chain methods like .upper(): all inside the braces.
Example 3: Alignment and Padding
for item, cost in [("Coffee", 3.5), ("Bagel", 2.0), ("Sandwich", 7.25)]: print(f"{item:<12}${cost:>6.2f}")
Multiline f-Strings
Use triple quotes for f-strings that span multiple lines. The f prefix works with both f"""...""" and f'''...'''.
name = "Kai" score = 92 total = 100 report = f""" Student: {name} Score: {score}/{total} Percent: {score / total:.1%} """ print(report)
Escaping Braces and Quotes
Need a literal curly brace in your output? Double it: {{ produces { and }} produces }.
lang = "Python" print(f"{{{lang}}} uses curly braces!") # {Python} uses curly braces! # Mix quote types freely: print(f"She said {'hello'}") # She said hello
Debugging with =
Python 3.8 added the self-documenting expression feature: append = after the expression to print both the expression text and its value.
x = 42 name = "Ada" print(f"{x=}") # x=42 print(f"{name.upper()=}") # name.upper()='ADA' print(f"{x * 2 + 1=}") # x * 2 + 1=85
Common Mistakes
f-String Cheat Sheet
| Feature | Syntax | Example Output |
|---|---|---|
| Variable | f"{x}" | 42 |
| Expression | f"{x+1}" | 43 |
| 2 decimals | f"{pi:.2f}" | 3.14 |
| Percentage | f"{0.85:.0%}" | 85% |
| Comma separator | f"{n:,}" | 1,000,000 |
| Left-align | f"{s:<10}" | hi |
| Right-align | f"{s:>10}" | hi |
| Debug | f"{x=}" | x=42 |
| Literal brace | f"{{" | { |
Question 1 of 5
What does this code print?
name = "Zara"
print(f"Hello, {name}!")
Question 2 of 5
Which f-string correctly displays \( 3.14159 \) rounded to two decimal places?
Question 3 of 5
What is the output of:
x = 5
print(f"{{x}} = {x}")
Question 4 of 5
Which statement about f-strings is false?
Question 5 of 5
What does f"{0.753:.0%}" produce?