String Formatting in Python
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
# Demo file so this example runs as-is (in your project this is your real results file)
pd.DataFrame({
"model_name": ["XGBoost", "RandomForest", "LogReg"],
"accuracy": [92.5, 89.123, 84.3],
"dataset": ["customer_churn", "fraud", "customer_churn"],
}).to_csv("model_results.csv", index=False)
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
Comparing the Three Formatting Styles
Python has three main ways to format strings: the old % operator, str.format and f-strings. All three support format specifications such as width and decimal places, but with different syntax: "%.2f" % x, "{:.2f}".format(x) and f"{x:.2f}" all produce the same text.
f-strings are the modern default because the value sits right next to its format. str.format remains useful when the template is stored separately, for example in a configuration file, and filled later.
The % style is mainly found in older code and in the logging module, which uses it for lazy formatting.
Worked Example: The Same Report Line Three Ways
One value is formatted with each style and the results are compared.
city, sales = "Karachi", 12345.678
a = "%s: %.2f" % (city, sales)
b = "{}: {:.2f}".format(city, sales)
c = f"{city}: {sales:.2f}"
print(a, b, c, sep="\n")
print(a == b == c)
template = "{city}: {sales:,.0f}"
print(template.format(city=city, sales=sales))
All three styles produce identical text. The stored template shows why str.format is useful when the layout is defined before the values are known, and the comma adds a thousands separator.
Practical Tips
Pick one style for each project and use it consistently. Mixed styles make code reviews harder and hide small differences such as rounding or padding.
For log messages, pass the values as arguments to the logging call, as in logger.info("%s rows", n), so formatting only happens when the message is actually written.
Common Mistakes
- Mixing styles in one project without reason.
- Using % formatting with a single tuple argument incorrectly.
- Building templates with f-strings, which run immediately.
- Forgetting that format specifications are shared across styles.
Quick Summary
- %, format and f-strings all work.
- f-strings are the modern default.
- str.format suits stored templates.
- Format specs look the same in all styles.
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()