String Formatting in Python – Complete Guide for Data Science 2026
String formatting is a core skill in data science for creating readable log messages, dynamic SQL queries, report strings, feature names, and preparing text for Regular Expressions and NLP models. In 2026, Python offers modern, clean, and efficient ways to format strings using f-strings and the .format() method, replacing older techniques like the % operator.
TL;DR — Modern String Formatting Methods
- f-strings (
f"...") → fastest and most readable for simple cases .format()→ powerful for complex templates and reuse%operator → legacy, avoid in new code- Supports alignment, precision, and type formatting
1. Modern f-strings (Recommended)
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. .format() Method – Powerful and Reusable
template = "Model {1} achieved {0:.2f}% accuracy on dataset {2}"
result = template.format(98.76, "XGBoost", "customer_churn")
print(result)
# Named placeholders for clarity
named = "User {name} scored {score:.2f}%"
print(named.format(name="Bob", score=87.5))
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
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 simple, one-off formatting
- Use
.format()when you need templates or named placeholders - Always prefer f-strings and
.format()over the old%operator - Use formatting specifiers (
:.2f,:,,:^10) for clean output - Keep formatting logic separate from business logic for maintainability
Conclusion
String formatting is a foundational skill that prepares you for more advanced Regular Expression work and text generation in data science. In 2026, f-strings and the .format() method provide the cleanest, most readable, and most efficient ways to create dynamic strings for logs, reports, queries, and features. Mastering these techniques makes your code significantly more professional and maintainable.
Next steps:
- Review your current string-building code and replace any manual concatenation or old
%formatting with modern f-strings or.format()