01 / 20
f"

f-Strings &
Formatting

Master Python's most powerful string formatting tool: f-strings. Learn to embed expressions, control decimal precision, align text, and build clean output.

Python

What Are f-Strings?

An f-string (formatted string literal) is a string that starts with the letter f before the opening quote. Inside the string, you place Python expressions inside curly braces {}, and Python evaluates them at runtime and inserts the result.

Python
name = "Alice"
age = 16
print(f"My name is {name} and I am {age} years old.")
Output
My name is Alice and I am 16 years old.

Why f-Strings Matter

Readable
Variables appear right where they'll be printed: no counting placeholders or commas.
Fast
f-strings are evaluated at runtime and are faster than .format() or % formatting.
Powerful
Embed any valid Python expression: math, function calls, conditionals, and more.

Anatomy of an f-String

f " Hello, {name} ! You got {score} " f prefix Expression (evaluated at runtime) Static text Expression

Expressions Inside Braces

You can put any valid Python expression inside the curly braces: not just variable names.

Python
x = 7
print(f"Double: {x * 2}")
print(f"Type:   {type(x).__name__}")
print(f"Upper:  {'hello'.upper()}")
print(f"Even?   {x % 2 == 0}")
Output
Double: 14
Type:   int
Upper:  HELLO
Even?   False

The Format Specifier

After the expression, add a colon : followed by a format specifier to control how the value is displayed.

{ price : >10 .2f } Expression Colon separator Alignment & width Precision & type

Formatting Numbers

Python
pi = 3.14159265
big = 1234567

print(f"2 decimals:  {pi:.2f}")
print(f"Percentage:  {0.856:.1%}")
print(f"With commas: {big:,}")
print(f"Scientific:  {big:.2e}")
Output
2 decimals:  3.14
Percentage:  85.6%
With commas: 1,234,567
Scientific:  1.23e+06
.2f
Fixed-point: 2 decimal places
.1%
Percentage: multiply by 100, 1 decimal
,
Thousands separator with commas
.2e
Scientific notation: 2 decimal places

Text Alignment & Width

Use < (left), > (right), or ^ (center) with a width number to pad output to a fixed column width.

Python
item = "Apples"
qty  = 42

print(f"|{item:<15}|{qty:>8}|")
print(f"|{'Oranges':<15}|{7:>8}|")
print(f"|{'TOTAL':^15}|{49:^8}|")
Output
|Apples         |      42|
|Oranges        |       7|
|     TOTAL     |   49   |

f-Strings vs. Other Methods

f-Strings .format() % Operator
Syntax f"{name}" "{}".format(name) "%s" % name
Readability Excellent Good Fair
Expressions ✓ Inline ✓ In args Limited
Speed Fastest Moderate Moderate
Python Version 3.6+ 2.7+ All

How to Apply f-Strings

1
Add the f prefix before the opening quote: f"..." or f'...'
2
Write your static text exactly as you want it to appear in the output.
3
Insert {expression} wherever you need a dynamic value: variable, calculation, or function call.
4
Add :specifier after the expression if you need to control width, alignment, decimals, or type.
5
Test your output. Print and verify alignment, precision, and edge cases (empty strings, zero, negatives).

Example: Receipt Formatter

Python
items = [("Coffee", 4.50), ("Bagel", 3.25), ("Juice", 5.99)]

print(f"{'Item':<12}{'Price':>8}")
print("-" * 20)

for name, price in items:
    print(f"{name:<12}${price:>7.2f}")

print("-" * 20)
total = sum(p for _, p in items)
print(f"{'Total':<12}${total:>7.2f}")
Output
Item           Price
--------------------
Coffee       $   4.50
Bagel        $   3.25
Juice        $   5.99
--------------------
Total        $  13.74

Example: Grade Report

Python
student = "Maya"
scores  = [88, 92, 75, 95, 83]
avg     = sum(scores) / len(scores)
highest = max(scores)
passed  = avg >= 70

print(f"""
Student: {student}
Average: {avg:.1f}
Highest: {highest}
Status:  {"PASS" if passed else "FAIL"}
""")
Output
Student: Maya
Average: 86.6
Highest: 95
Status:  PASS

Example: Debugging with =

Python 3.8+ added a handy debug shortcut: add = after an expression to print both the expression text and its value.

Python 3.8+
x = 42
name = "Alice"

print(f"{x=}")
print(f"{name=}")
print(f"{x * 2 + 1=}")
print(f"{len(name)=}")
Output
x=42
name='Alice'
x * 2 + 1=85
len(name)=5

Format Specifier Cheat Sheet

Specifier Meaning Example Result
.2f 2 decimal places f"{3.14159:.2f}" 3.14
.1% Percentage f"{0.856:.1%}" 85.6%
, Thousands separator f"{50000:,}" 50,000
>10 Right-align, width 10 f"{'hi':>10}"         hi
<10 Left-align, width 10 f"{'hi':<10}" hi        
^10 Center-align, width 10 f"{'hi':^10}"     hi    
08d Zero-padded integer f"{42:08d}" 00000042

Common Mistakes

✕ Forgetting the f
Writing "{name}" instead of f"{name}" prints the literal text {name}.
✕ Matching Quotes
Using the same quote inside braces: f"{'hello'}" works, but f"{"hello"}" causes a syntax error.
✕ Backslashes in Braces
You cannot use \n inside the {} expression. Assign to a variable first, then reference it.

Question 1 of 5

What does the following code print?
x = 5; print(f"Value: {x * 3}")

Question 2 of 5

Which format specifier rounds 3.14159 to 2 decimal places?

Question 3 of 5

What does f"{42:08d}" produce?

Question 4 of 5

Which correctly prints a literal curly brace { inside an f-string?

Question 5 of 5

What does the following code output?
name = "Jo"; print(f"|{name:*^10}|")