format() is Python’s versatile string formatting method (and f-string foundation) that lets you embed expressions, control alignment, precision, padding, and thousands separators — creating readable, dynamic strings for logging, reports, templates, and UI. In 2026, .format() remains widely used (especially in legacy code and libraries), while f-strings (f"...{expr}...") dominate modern Python for simplicity and speed. Both support powerful format specifiers (:.2f, :,d, :>10, :^20) and are vectorized in pandas/Polars/Dask for large-scale formatting of data columns (earthquake reports, metrics, tables).
Here’s a complete, practical guide to string formatting with format() and f-strings in Python: basic placeholders, format specifiers, real-world patterns (earthquake summary tables, logging, dynamic messages), and modern best practices with type hints, performance, alignment, and integration with pandas/Polars/Dask/NumPy.
Basic formatting — positional, named, and f-string equivalents.
# .format() positional
print("Mag: {}, Place: {}".format(7.2, "Japan"))
# Mag: 7.2, Place: Japan
# Named placeholders
print("Mag: {mag}, Place: {place}".format(mag=7.2, place="Japan"))
# f-strings (preferred in modern code)
mag = 7.2
place = "Japan"
print(f"Mag: {mag}, Place: {place}")
# Expressions inside f-strings
print(f"Strong quake: {mag >= 7.0}") # Strong quake: True
print(f"Double mag: {mag * 2:.1f}") # Double mag: 14.4
Format specifiers — control precision, alignment, padding, signs, thousands separators.
pi = 3.14159265359
count = 1234567
negative = -42.5
# Precision & type
print("{:.2f}".format(pi)) # 3.14
print(f"{pi:.4f}") # 3.1416
# Integer with commas
print("{:,}".format(count)) # 1,234,567
print(f"{count:,}") # 1,234,567
# Alignment & padding
print("{:>10}".format("right")) # right
print("{:<10}".format("left")) # left
print("{:^10}".format("center")) # center
# Sign control
print("{:+.2f}".format(positive)) # +42.50
print("{:+.2f}".format(negative)) # -42.50
# Zero padding
print("{:010.2f}".format(pi)) # 000003.14
print(f"{pi:010.2f}") # 000003.14
Real-world pattern: formatting earthquake summary reports & tables.
import pandas as pd
df = pd.DataFrame({
'place': ['Japan', 'Chile', 'Alaska'],
'mag': [7.1, 6.8, 8.2],
'depth': [25.0, 45.5, 10.0],
'time': pd.to_datetime(['2025-03-01', '2025-03-02', '2025-03-03'])
})
# Format report rows
for _, row in df.iterrows():
print(
f"{row['time']:%Y-%m-%d} | "
f"Mag: {row['mag']:.1f} | "
f"Depth: {row['depth']:.1f} km | "
f"{row['place']:<15}"
)
# 2025-03-01 | Mag: 7.1 | Depth: 25.0 km | Japan
# ...
# Pandas Styler for formatted output
styled = df.style.format({
'mag': '{:.1f}',
'depth': '{:.1f} km',
'time': '{:%Y-%m-%d}'
}).set_caption("Recent Major Earthquakes")
print(styled.to_string())
Best practices for format() & f-strings in Python & data workflows. Prefer f-strings (f"...") — faster, more readable, supports expressions. Modern tip: use Polars .with_columns(pl.col('mag').round(1)) — for formatted columns; Dask for distributed formatting. Use format specifiers — :.2f, :,d, :>10, :^20. Add type hints — def format_event(mag: float, place: str) -> str. Use str.format_map() — with dicts: "Mag: {mag}".format_map(locals()). Avoid % formatting — deprecated, less safe. Use format() in logging — logger.info("Mag: {:.1f} at {}".format(mag, place)). Use f-strings in f-strings — f"Mag: {mag:.1f}". Use !r — for repr: f"{obj!r}". Use !s — for str. Use {expr=} — debug: f"{mag=:.2f}" ? "mag=7.20". Use {variable=} — in f-strings for quick debug. Use string.Template — for simple substitution. Use jinja2 — for complex templates. Use rich — for styled console output. Profile performance — f-strings fastest, then .format(). Use str.join() — for large concatenations. Use io.StringIO — for building large strings.
format() & f-strings create dynamic, formatted strings — positional/named placeholders, precision, alignment, padding, thousands separators. In 2026, prefer f-strings for speed/readability, use specifiers for control, integrate with pandas/Polars/Dask for column formatting, and use {var=} for debug. Master string formatting, and you’ll produce clean, professional reports, logs, and outputs in any Python workflow.
Next time you need dynamic strings — use f-strings or format(). It’s Python’s cleanest way to say: “Insert values into text — beautifully, precisely, and efficiently.”