This content originally appeared on Level Up Coding – Medium and was authored by Ebo Jackson
F-strings, introduced in Python 3.6, are a concise and readable way to embed expressions inside string literals. Using the f prefix, they allow developers to format strings dynamically by directly incorporating variables, expressions, and even complex operations within curly braces {}. This article explores the essential features of f-strings, showcasing their versatility and power in Python programming.
Why F-strings?
Before f-strings, Python offered methods like %-formatting and str.format(). While functional, these approaches were often verbose and prone to errors. F-strings provide a more intuitive syntax, reducing boilerplate code and improving readability. They are now the preferred method for string formatting in modern Python.
Basic Syntax
An f-string starts with an f or F before the string literal. Inside the string, expressions or variables are enclosed in curly braces {} and evaluated at runtime.
name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # Output: Hello, Alice! You are 30 years old.
Embedding Expressions
F-strings can evaluate expressions directly within the curly braces, making them highly flexible.
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result) # Output: The sum of 5 and 10 is 15.
You can include arithmetic operations, function calls, or even list comprehensions:
numbers = [1, 2, 3]
squared = f"Squared numbers: {[n**2 for n in numbers]}"
print(squared) # Output: Squared numbers: [1, 4, 9]
Formatting Numbers
F-strings support precise control over numeric formatting, such as specifying decimal places, padding, or alignment.
Floating-Point Precision
Use :.nf to control the number of decimal places for floats:
pi = 3.14159
formatted = f"Pi to 2 decimal places: {pi:.2f}"
print(formatted) # Output: Pi to 2 decimal places: 3.14
Padding and Alignment
You can align text or pad numbers with spaces or zeros:
number = 42
padded = f"Padded number: {number:05d}" # Zero-padding to 5 digits
print(padded) # Output: Padded number: 00042
# Alignment: < (left), > (right), ^ (center)
name = "Bob"
aligned = f"|{name:<10}|{name:^10}|{name:>10}|"
print(aligned) # Output: |Bob | Bob | Bob|
Percentage Formatting
Format numbers as percentages:
progress = 0.756
percentage = f"Progress: {progress:.1%}"
print(percentage) # Output: Progress: 75.6%
Working with Dates
F-strings integrate seamlessly with Python’s datetime module for formatting dates and times.
from datetime import datetime
now = datetime.now()
formatted_date = f"Today: {now:%Y-%m-%d %H:%M:%S}"
print(formatted_date) # Output: Today: 2025-06-04 15:36:00 (example timestamp)
Multiline F-strings
F-strings can span multiple lines using triple quotes, making them ideal for complex string formatting:
name = "Charlie"
items = ["apple", "banana", "orange"]
order = f"""Order Summary:
Customer: {name}
Items: {', '.join(items)}
Total: ${len(items) * 2.5:.2f}"""
print(order)
# Output:
# Order Summary:
# Customer: Charlie
# Items: apple, banana, orange
# Total: $7.50
Debugging with =
Since Python 3.8, f-strings support the = specifier for debugging, which includes the expression and its value:
x = 10
print(f"{x=}") # Output: x=10
This is particularly useful for inspecting variables during development.
Escaping and Raw F-strings
To include literal curly braces, double them:
code = f"Use {{braces}} in f-strings"
print(code) # Output: Use {braces} in f-strings
For strings with many backslashes (e.g., regex), combine f with r for raw f-strings:
path = r"C:\Users"
print(fr"Path: {path}") # Output: Path: C:\Users
Calling Methods and Accessing Attributes
F-strings can invoke methods or access object attributes directly:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "Hi!"
person = Person("David")
info = f"{person.name} says {person.greet()}"
print(info) # Output: David says Hi!
Limitations and Best Practices
- Performance: F-strings are generally faster than %-formatting or str.format() because they are evaluated at compile time.
- Security: Avoid using f-strings with untrusted input, as they can execute arbitrary code (e.g., f"{__import__('os').system('rm -rf /')}"). Use safer alternatives like str.format() for user input.
- Readability: Keep expressions simple within f-strings to maintain clarity. Complex logic is better handled outside the string.
Conclusion
F-strings are a powerful, concise, and readable tool in Python’s string formatting arsenal. From basic variable substitution to advanced formatting and debugging, they streamline code and enhance productivity. By mastering f-strings, Python developers can write cleaner, more maintainable code, making them a true powerhouse of the language.
F-strings: The Powerhouse of Python was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding – Medium and was authored by Ebo Jackson