01 / 21
f { }

Python
f-Strings

Master formatted string literals to embed expressions directly inside strings: the modern, readable way to build dynamic output in Python.

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.

Python
name = "Alice"
age  = 16

print(f"My name is {name} and I am {age} years old.")

Why f-Strings Matter

Readable
Variables appear inline, exactly where they show up in the output: no guessing which argument goes where.
Concise
One prefix letter f replaces verbose method calls and clumsy + concatenation.
Fast
f-Strings are evaluated at runtime by the interpreter and are faster than .format() or % formatting.

Anatomy of an f-String

f " Hello, { name } ! You are { age } . " prefix expression expression ↓ Hello, Alice! You are 16.

The Core Rule

Python
# 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.

f" Price: { cost : .2f } " : colon format spec → Price: 9.99
Python
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

1
Start with the f prefix before the opening quote: f"..." or f'...'.
2
Write your static text as you normally would inside the quotes.
3
Insert {expression} wherever you want a dynamic value.
4
Add :format_spec after the expression if you need to control decimal places, alignment, padding, etc.
5
Run your code: Python evaluates each expression and builds the final string automatically.

Example 1: Greeting

Python
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

Python
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

Python
for item, cost in [("Coffee", 3.5), ("Bagel", 2.0), ("Sandwich", 7.25)]:
    print(f"{item:<12}${cost:>6.2f}")
<12
Left-align in a field 12 characters wide
>6.2f
Right-align a float in 6 characters with 2 decimal places

Multiline f-Strings

Use triple quotes for f-strings that span multiple lines. The f prefix works with both f"""...""" and f'''...'''.

Python
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 }.

Python
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.

Python 3.8+
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

✕ Forgetting the f
Writing "{name}" without the f prefix gives the literal text {name}, not the variable's value.
✕ Backslash in Braces
You cannot use \n or \\ directly inside {}. Assign to a variable first, then embed the variable.
✕ Same Quote Nesting
Using f"{"hi"}" causes a SyntaxError. Use different quote types: f"{'hi'}".

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?