F-Strings
Formatting strings with f-strings -- Python's modern, readable way to embed expressions in text.
2 min read
Building a string out of variables used to mean chaining + and str() calls, or reaching for .format(). Since Python 3.6, f-strings do it more directly, and they're now the standard way to format strings in Python.
The basics
Prefix a string with f and embed any expression in {}:
name = "Ada"
age = 25
print(f"{name} is {age} years old.")
# Ada is 25 years old.Compare that to the concatenation approach it replaced:
print(name + " is " + str(age) + " years old.")The f-string version needs no manual str() conversion — Python converts whatever's inside the braces automatically — and it reads in the same order you'd say it out loud.
Any expression works inside the braces
It's not limited to plain variable names:
price = 19.99
quantity = 3
print(f"Total: {price * quantity}")
# Total: 59.97
items = ["eggs", "milk", "bread"]
print(f"You have {len(items)} items")
# You have 3 itemsYou can even call functions or access dictionary keys and object attributes directly inside the braces.
Formatting numbers
A colon after the expression introduces a format spec, controlling things like decimal places, padding, and thousands separators:
price = 19.9
print(f"${price:.2f}") # $19.90 -- 2 decimal places
print(f"{1000000:,}") # 1,000,000 -- thousands separator
print(f"{0.856:.1%}") # 85.6% -- percentage
print(f"{42:05d}") # 00042 -- zero-padded to 5 digits.2f means "fixed-point with 2 decimal places" — invaluable for displaying currency without manual rounding logic.
Debugging with =
A lesser-known but genuinely useful trick: adding = inside the braces prints both the expression and its value, handy for quick debugging without writing a separate print("x:", x):
x = 10
print(f"{x=}")
# x=10Multi-line f-strings
Triple-quoted strings can be f-strings too:
name = "Ada"
score = 95
report = f"""
Name: {name}
Score: {score}
Grade: {"Pass" if score >= 60 else "Fail"}
"""
print(report)That ternary-style expression ("Pass" if score >= 60 else "Fail") works inside an f-string exactly as it would anywhere else in Python — a preview of the conditional expressions covered in the next section on control flow.
F-strings are the default choice for string formatting in modern Python. You'll see them in nearly every example for the rest of this course.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.