Python Basics — f-Strings
f-Strings
f-strings (formatted string literals) were introduced in Python 3.6 and are the recommended way to format strings. They’re fast, readable, and support inline expressions.
Basic Syntax
Prefix a string with f or F and put expressions inside curly braces {}:
name = "Alice"
age = 25
print(f"Hello, {name}!") # Hello, Alice!
print(f"{name} is {age} years old.") # Alice is 25 years old.
Expressions Inside f-Strings
You can put any valid Python expression inside the braces:
# Arithmetic
print(f"2 + 3 = {2 + 3}") # 2 + 3 = 5
# Function calls
print(f"Name: {'alice'.title()}") # Name: Alice
# Method calls
items = [1, 2, 3]
print(f"Items: {len(items)}") # Items: 3
# Conditional expressions
age = 20
print(f"Status: {'adult' if age >= 18 else 'minor'}")
# Status: adult
Formatting Numbers
pi = 3.14159265
# Decimal places
print(f"Pi: {pi:.2f}") # Pi: 3.14
print(f"Pi: {pi:.4f}") # Pi: 3.1416
# Comma separator
big_number = 1234567
print(f"Population: {big_number:,}") # Population: 1,234,567
# Percentage
rate = 0.856
print(f"Success: {rate:.1%}") # Success: 85.6%
# Zero padding
code = 42
print(f"Code: {code:05}") # Code: 00042
# Sign display
value = 42
print(f"Positive: {value:+}") # Positive: +42
print(f"Negative: {-value:+}") # Negative: -42
Formatting Dates
from datetime import datetime
now = datetime.now()
print(f"Date: {now:%Y-%m-%d}") # Date: 2025-03-03
print(f"Time: {now:%H:%M:%S}") # Time: 14:30:45
print(f"Full: {now:%B %d, %Y %I:%M %p}") # Full: March 03, 2025 02:30 PM
Multi-Line f-Strings
name = "Alice"
age = 25
city = "NYC"
# Using parentheses
message = (
f"Name: {name}\n"
f"Age: {age}\n"
f"City: {city}"
)
print(message)
# Name: Alice
# Age: 25
# City: NYC
# Using triple quotes
report = f"""
Student Report
--------------
Name: {name}
Age: {age}
City: {city}
"""
print(report)
f-String Debugging (= modifier)
Python 3.8+ added the = modifier that shows both the expression and its value:
x = 10
y = 20
print(f"{x = }") # x = 10
print(f"{y = }") # y = 20
print(f"{x + y = }") # x + y = 30
print(f"{x * y = }") # x * y = 200
name = "Alice"
print(f"{name = }") # name = 'Alice'
print(f"{len(name) = }") # len(name) = 5
This is incredibly useful for quick debugging — no need to type print(f"x = {x}").
Alignment in f-Strings
# Left-align (<), right-align (>), center (^)
print(f"{'left':<20}") # left
print(f"{'right':>20}") # right
print(f"{'center':^20}") # center
# With fill character
print(f"{'Title':*^30}") # ************Title*************
print(f"{'Score':->20}") # ---------------Score
print(f"{42:0>5}") # 00042
Nested f-Strings
You can nest f-strings in Python 3.12+:
# Works in Python 3.12+
# value = 42
# print(f"{f'{value:05}'}") # 00042
# For older Python, use a variable
formatted = f"{42:05}"
print(f"Result: {formatted}") # Result: 00042
Escaping Braces
To include literal curly braces, double them:
print(f"{{Hello}}") # {Hello}
print(f"x = {10}") # x = 10
print(f"x = {{10}}") # x = {10}
# Useful for JSON-like output
name = "Alice"
print(f'{{"name": "{name}"}}')
# {"name": "Alice"}
Performance
f-strings are the fastest string formatting method in Python:
# f-strings are compiled at parse time, making them faster
# than % formatting or str.format()
name = "Alice"
# Fastest
f"Hello, {name}!"
# Slower
"Hello, {}!".format(name)
# Slower
"Hello, %s!" % name
Common Mistakes
| Mistake | Example | Fix |
|---|---|---|
Missing f prefix |
"{name}" |
f"{name}" |
| Backslash in braces | f"{'\\n'}" |
Use a variable |
| Using quotes inside braces | f"{'it's'}" |
Mix quote types |
Summary
- f-strings use the
f"..."prefix with{expressions} - Support any Python expression inside braces
- Format numbers with
:.2f,:,,:.1%,:05 - Format dates with
:%Y-%m-%d,:%H:%M:%S - Use
=modifier for quick debugging (Python 3.8+) - Use
<,>,^for alignment - Double braces
{{}}for literal braces - f-strings are the fastest and recommended formatting method
Next up: Format Specifiers →