Format Specifiers in Python

Regular Expressions Mar 20, 2026

Format Specifiers in Python

Format specifiers are the powerful mini-language inside f-strings and .format() that let you control exactly how values appear when turned into strings. In data science, they are used constantly for creating clean reports, log messages, SQL queries, feature names, and formatted output. Mastering format specifiers makes your text generation professional, consistent, and highly readable.

TL;DR — Most Useful Format Specifiers

  • :.2f → float with 2 decimal places
  • :, → add thousand separators
  • :^10 → center in 10 characters
  • :>10 → right-align
  • :.0% → percentage
  • :Y-%m-%d → date formatting (via strftime inside)

1. Basic Format Specifiers

score = 95.7534
amount = 1250.75
name = "Alice"

print(f"Score: {score:.2f}")           # 95.75
print(f"Amount: ${amount:,.2f}")       # $1,250.75
print(f"Name: {name:^10}")             # "  Alice   " (centered)
print(f"Name: {name:>10}")             # "     Alice" (right-aligned)

2. 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: Clean report output
for row in df.itertuples():
    print(f"Model {row.model_name:15} achieved {row.accuracy:.2f}% accuracy")

# Example 2: Formatted feature importance (demo values)
feature_importance = {"amount": 0.4213, "quantity": 0.2875, "region": 0.0912}
for feature, score in feature_importance.items():
    print(f"{feature:20} : {score:6.2%}")

# Example 3: Dynamic SQL with formatting
threshold = 1000
query = f"SELECT customer_id, order_date FROM sales WHERE amount > {threshold:,.2f}"

3. Advanced Format Specifiers

# Percentage, scientific notation, padding
print(f"Progress: {0.856:.1%}")        # 85.6%
print(f"Large number: {123456789:,.0f}") # 123,456,789

# Date formatting inside f-strings
from datetime import date
d = date(2026, 3, 19)
print(f"Report date: {d:%A, %B %d, %Y}")   # Thursday, March 19, 2026

4. Best Practices in 2026

  • Use f-strings with format specifiers for most formatting tasks
  • Define common formats as constants for consistency across your project
  • Use alignment specifiers (:^, :>, :<) for clean tables and reports
  • Always include thousand separators (:,) for large numbers
  • Combine with Regular Expressions when building dynamic patterns

Reading a Format Specification

A format specification follows the colon and has a fixed order: fill, align, sign, width, thousands separator, precision and type. For example, {:>10,.2f} right-aligns a number in 10 characters with commas and two decimals.

Common types are f for fixed decimals, e for scientific notation, % for percentages (the value is multiplied by 100) and d for integers. Using d with a float raises ValueError.

Width and alignment help build simple aligned tables in logs and console reports.

Worked Example: An Aligned Console Table

Model metrics are printed in aligned columns.

results = [("Logistic", 0.8734, 1520.5), ("Random Forest", 0.9125, 98765.25)]

print(f"{'model':<15}{'acc':>8}{'cost':>12}")
for name, acc, cost in results:
    print(f"{name:<15}{acc:>8.1%}{cost:>12,.2f}")

print(f"{0.000123:.2e}", f"{42:05d}", f"{-3:+d}")

Names are left-aligned and numbers right-aligned, so the columns line up. The % type shows 87.3% and 91.2%, and the last line shows scientific notation, zero padding and an explicit sign.

Practical Tips

Choose precision from the audience. Two decimals suit money, one decimal suits percentages in reports, and scientific notation suits very small or very large values such as p-values and error rates.

Keep the formatting at the very end of the pipeline. Formatted values are strings, so rounding or formatting too early breaks later calculations and sorting.

For wide tables, compute the column widths from the longest value instead of hard-coding them.

Check the output in the place it will be shown, since fonts and widths differ between consoles, files and dashboards.

Common Mistakes

  • Writing the parts of a specification in the wrong order.
  • Using d with floats.
  • Multiplying by 100 before using the % type.
  • Choosing a width smaller than the values.

Quick Summary

  • Specs follow fill, align, sign, width, comma, precision, type.
  • % multiplies by 100.
  • e gives scientific notation.
  • Width and alignment build tables.

Conclusion

Format specifiers are a powerful extension of string formatting that every data scientist should master. In 2026, using them inside f-strings and .format() lets you create professional, consistent, and readable output for logs, reports, queries, and features with minimal code. These techniques prepare you perfectly for more advanced Regular Expression work and make your entire text-processing pipeline cleaner and more maintainable.

Next steps:

  • Review your current string formatting code and apply format specifiers for better alignment, precision, and readability

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