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.
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.
name = "Alice" age = 16 print(f"My name is {name} and I am {age} years old.")
My name is Alice and I am 16 years old.
Why f-Strings Matter
.format() or % formatting.Anatomy of an f-String
Expressions Inside Braces
You can put any valid Python expression inside the curly braces: not just variable names.
x = 7 print(f"Double: {x * 2}") print(f"Type: {type(x).__name__}") print(f"Upper: {'hello'.upper()}") print(f"Even? {x % 2 == 0}")
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.
Formatting Numbers
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}")
2 decimals: 3.14 Percentage: 85.6% With commas: 1,234,567 Scientific: 1.23e+06
Text Alignment & Width
Use < (left), > (right), or ^ (center) with a width number to pad output to a fixed column width.
item = "Apples" qty = 42 print(f"|{item:<15}|{qty:>8}|") print(f"|{'Oranges':<15}|{7:>8}|") print(f"|{'TOTAL':^15}|{49:^8}|")
|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
f"..." or f'...'Example: Receipt Formatter
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}")
Item Price -------------------- Coffee $ 4.50 Bagel $ 3.25 Juice $ 5.99 -------------------- Total $ 13.74
Example: Grade Report
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"} """)
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.
x = 42 name = "Alice" print(f"{x=}") print(f"{name=}") print(f"{x * 2 + 1=}") print(f"{len(name)=}")
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
"{name}" instead of f"{name}" prints the literal text {name}.f"{'hello'}" works, but f"{"hello"}" causes a syntax error.\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}")
x * 3 (which is 5 * 3 = 15) and inserts the result. The curly braces do not appear in the output.Question 2 of 5
Which format specifier rounds 3.14159 to 2 decimal places?
:.2f where the dot specifies precision, 2 is the number of decimal places, and f stands for fixed-point notation.Question 3 of 5
What does f"{42:08d}" produce?
0 is the fill character, 8 is the total width, and d is for decimal integer. So 42 is right-aligned in 8 characters, padded with zeros on the left: 00000042.Question 4 of 5
Which correctly prints a literal curly brace { inside an f-string?
{ or } in an f-string, you double it: {{ becomes { and }} becomes }. So f"value: {{x}}" prints value: {x}.Question 5 of 5
What does the following code output?name = "Jo"; print(f"|{name:*^10}|")
*^10 means: use * as the fill character, ^ center-align, in a field of 10 characters wide. "Jo" is 2 characters, so 8 asterisks are split evenly: 4 on each side.