Formatted String Literals (f-strings) in Python – Complete Guide for Data Science 2026
Formatted string literals, commonly known as **f-strings**, are the most modern, readable, and performant way to embed variables and expressions inside strings in Python. Introduced in Python 3.6, f-strings have become the standard for data science in 2026 because they are fast, concise, and support powerful formatting specifiers directly inside the string.
TL;DR — Why f-strings Are Preferred in 2026
- Fastest string formatting method
- Most readable (variables appear directly inside the string)
- Supports expressions, format specifiers, and even function calls
- Ideal for logs, reports, SQL queries, feature names, and dynamic text
1. Basic f-string Syntax
name = "Alice"
score = 95.75
model = "random_forest"
message = f"User {name} achieved {score:.2f}% accuracy with {model} model"
print(message)
# With expressions
total = 1250.75
print(f"Total sales: ${total:,.2f}")
2. Advanced f-string Features
# Format specifiers
print(f"Score: {score:>8.2f}") # right-aligned, 2 decimals
print(f"Large number: {1234567:,.0f}") # thousand separators
# Expressions and function calls
data = [10, 20, 30]
print(f"Average: {sum(data)/len(data):.2f}")
# Date formatting inside f-strings
from datetime import date
d = date(2026, 3, 20)
print(f"Report date: {d:%A, %B %d, %Y}")
3. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("model_results.csv")
# Example 1: Dynamic log messages
for row in df.itertuples():
log = f"Model {row.model_name} achieved {row.accuracy:.2f}% on {row.dataset}"
print(log)
# Example 2: Build feature names dynamically
prefix = "feature_"
features = ["amount", "quantity", "profit"]
full_features = [f"{prefix}{f}" for f in features]
# Example 3: SQL query construction
columns = ["customer_id", "order_date", "amount"]
query = f"SELECT {', '.join(columns)} FROM sales WHERE amount > 1000"
4. Best Practices in 2026
- Use f-strings for almost all string formatting tasks
- Keep complex logic outside the f-string when readability matters
- Use format specifiers (
:.2f,:,,:^10) for clean output - Define common templates as constants when they are reused
- Combine with Regular Expressions when building dynamic patterns
Conclusion
Formatted string literals (f-strings) are the modern standard for string formatting in Python. In 2026 data science projects, f-strings make your code cleaner, faster, and more readable than older methods like .format() or the % operator. Mastering f-strings prepares you perfectly for building dynamic strings, logs, reports, and complex Regular Expression patterns.
Next steps:
- Review your current string-building code and convert it to modern f-strings for improved readability and performance