A Guide to Python's f-strings: The Best Way to Format Strings
A comprehensive guide to f-strings (formatted string literals) in Python. Learn why they are the modern, clean, and fast way to embed expressions inside string literals.
Python has gone through several different ways of formatting strings over the years. From the old C-style %
formatting to the more flexible str.format()
method, each had its pros and cons. But since the introduction of formatted string literals, or f-strings, in Python 3.6, there has been a clear winner.
f-strings are the most readable, concise, and often the fastest way to format strings in modern Python.
What are f-strings?
An f-string is a string literal that is prefixed with the letter f
or F
. These strings can contain expressions inside curly braces {}
. These expressions are evaluated at runtime and then formatted into the string.
A Simple Example:
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)
# Output: My name is Alice and I am 30 years old.
This is much cleaner and more readable than the older methods.
The Old Way (%
formatting):
message = "My name is %s and I am %d years old." % (name, age)
The str.format()
Way:
message = "My name is {} and I am {} years old.".format(name, age)
The f-string version is clearly superior. The variables are right there inside the string, so you don't have to look back and forth to see what's being inserted.
You Can Put Any Valid Expression Inside
The real power of f-strings is that you can put almost any valid Python expression inside the curly braces.
Calling functions:
message = f"My name in uppercase is {name.upper()}.
Performing calculations:
message = f"In 5 years, I will be {age + 5} years old."
Accessing dictionary values:
user = {"name": "Bob", "id": 456}
message = f"User {user['name']} has ID {user['id']}."
Formatting Options
f-strings also support a powerful mini-language for formatting the output of the expression. You add a colon (:
) after the expression to specify the format.
Formatting numbers:
price = 49.99
# Format as a float with 2 decimal places
message = f"The price is ${price:.2f}."
# Output: The price is $49.99.
# Add comma as a thousands separator
large_number = 1234567
message = f"The number is {large_number:,}."
# Output: The number is 1,234,567.
Formatting dates:
from datetime import datetime
now = datetime.now()
# Format a date
message = f"Today is {now:%Y-%m-%d}.
# Output: Today is 2020-04-20.
Padding and alignment:
for i in range(3):
# Pad with zeros to a width of 3
print(f"File number: {i:03d}")
# Output:
# File number: 000
# File number: 001
# File number: 002
A Note on Braces
If you need to include a literal curly brace {
or }
inside an f-string, you can escape it by doubling it.
message = f"To create a dictionary, use {{'key': 'value'}}."
# Output: To create a dictionary, use {'key': 'value'}.
Conclusion
f-strings are a fantastic addition to the Python language. They are more readable, more concise, and less error-prone than previous methods of string formatting. For any new Python code you write, f-strings should be your default choice for composing strings. They are a perfect example of Python's focus on developer happiness and code readability.