String Formatting in Python

Regular Expressions Mar 20, 2026

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()

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices