Master Python f-strings with this definitive guide! Learn syntax, formatting tricks, multiline f-strings, expressions, and advanced use cases with clear examples.
F-strings (formatted string literals) are a feature introduced in Python 3.6 that provide a concise and readable way to embed expressions inside string literals. The “f” stands for “formatted” - these strings are evaluated at runtime.
The basic syntax is simple - prefix your string with ‘f’ or ‘F’ and include expressions in curly braces {}
:
f"string text {expression} more text"
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.")
def greet(name):
return f"Hello, {name}!"
print(f"{greet('Bob')} How are you today?")
price = 19.99
quantity = 3
print(f"Total: ${price * quantity:.2f}")
Instructions
Examples
# Task 5.1: Use f-strings
name = "Ahmad"
age = 30
print(f"My name is {name} and I am {age} years old.")
user = {"name": "John", "last_login": "2023-04-15"}
print(f"User {user['name']} last logged in on {user['last_login']}")
filename = "report.pdf"
size = 2.5 # in MB
print(f"File '{filename}' is {size:.1f} MB ({size*1024:.0f} KB)")
response = {"status": "success", "data_count": 42, "time": 0.45}
print(f"API call {response['status']}. Returned {response['data_count']} items in {response['time']}s")
radius = 5.5
area = 3.14159 * radius**2
print(f"A circle with radius {radius} has area {area:.2f}")
x = 10
y = 20
print(f"DEBUG: x={x}, y={y}, x*y={x*y}")
Video Tutorial: Python f-Strings Explained - What Does print(f’{a=}’) Do?
for more details, see Python f-Strings with = and Format Specifiers (Debugging Made Easy)
value = 123.456789
print(f"Default: {value}")
print(f"2 decimal places: {value:.2f}")
print(f"Scientific notation: {value:.2e}")
print(f"Percentage: {0.25:.1%}")
item = "Apple"
price = 0.99
print(f"{item:10} - ${price:5.2f}") # Left-aligned
print(f"{item:>10} - ${price:5.2f}") # Right-aligned
from datetime import datetime
today = datetime.now()
print(f"Today is {today:%B %d, %Y}")
F-strings have become the preferred string formatting method in modern Python due to their clarity and efficiency. They’re widely used in logging, debugging, report generation, and anywhere you need to combine variables with text.
Tutorials, Roadmaps, Bootcamps & Visualization Projects