A Guide to Python F-Strings: The Best Way to Format Strings
Discover the power and simplicity of Python's f-strings. This guide covers the basics, formatting options, and why they are the modern, preferred way to build strings.
For years, Python developers had several options for formatting strings: the %
operator, str.format()
, and string.Template
. While they all work, none of them are as clean, readable, and powerful as the modern standard: f-strings, officially known as Formatted String Literals.
Introduced in Python 3.6, f-strings provide a concise and convenient way to embed expressions inside string literals for formatting. If you're not using them for all your string formatting needs, you're missing out.
The Basics
An f-string is a string literal that is prefixed with the letter f
or F
. You can then embed expressions inside curly braces {}
directly within the string, and they will be evaluated at runtime and included in the result.
The Old Way (str.format()
):
name = "Alice"
age = 30
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
print(greeting)
The F-String Way:
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
The f-string version is more readable because the variables are placed directly where they will appear in the string. You don't have to look back and forth between the string and the .format()
call.
You Can Put (Almost) Anything in the Braces
The real power of f-strings is that you can put almost any valid Python expression inside the curly braces.
Calculations:
print(f"Five plus ten is {5 + 10}.")
# Output: Five plus ten is 15.
Function Calls:
name = "Bob"
print(f"Hello, {name.upper()}!")
# Output: Hello, BOB!
Object Properties:
from datetime import datetime
now = datetime.now()
print(f"The current year is {now.year}.")
# Output: The current year is 2023.
Powerful Formatting Options
F-strings also support a powerful mini-language for formatting the output of the expressions. You add a colon :
after the expression to specify the format.
Formatting Numbers
You can easily format floating-point numbers to a specific number of decimal places.
price = 49.95
tax = 0.07
total = price * (1 + tax)
print(f"Total price: ${total:.2f}")
# Output: Total price: $53.45
Formatting Dates
You can format datetime
objects using the standard strftime
codes.
from datetime import datetime
today = datetime.now()
print(f"Today's date is {today:%Y-%m-%d}.")
# Output: Today's date is 2023-02-25.
Padding and Alignment
You can control the alignment and padding of your strings, which is useful for creating tables or other formatted text.
items = {"Apples": 5, "Bananas": 12, "Cherries": 3}
for item, count in items.items():
# Left-align the item in a space of 10 characters
# Right-align the count in a space of 3 characters
print(f"{item:<10} | {count:>3}")
# Output:
# Apples | 5
# Bananas | 12
# Cherries | 3
A Note on Debugging
Since Python 3.8, f-strings have a handy shortcut for debugging. By adding an equals sign =
after an expression, the f-string will print both the expression and its value.
user_id = 123
username = "testuser"
print(f"{user_id=} {username=}")
# Output: user_id=123 username='testuser'
This is a fantastic and concise way to print out variable values while debugging, saving you from typing print("user_id=", user_id)
.
Conclusion
F-strings are faster, more readable, and more concise than any of the other string formatting methods in Python. They are a clear example of how the language has evolved to make developers' lives easier. For any new Python code you write, f-strings should be your default choice for all your string formatting needs.