Methods for 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 several modern and efficient methods for formatting strings. Mastering these techniques makes your code cleaner, more maintainable, and significantly more professional.
TL;DR — Modern Formatting Methods
- f-strings (
f"...") → fastest and most readable for simple cases - .format() → powerful for complex templates and reuse
- str.format_map() → advanced mapping from dictionaries
- Avoid the legacy
%operator in new code
1. f-strings – The Modern Standard
name = "Alice"
score = 95.75
model = "random_forest"
message = f"User {name} achieved {score:.2f}% accuracy with {model} model"
print(message)
# Expressions inside f-strings
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 with f-strings
for row in df.itertuples():
log = f"Model {row.model_name} achieved {row.accuracy:.2f}% on {row.dataset}"
print(log)
# Example 2: Building 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 methods are 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. 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()