How do you format numbers with commas as thousands separators in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you format numbers with commas as thousands separators in Python?

message-square
0

Use an f-string with a comma format specifier—such as f"{num:,}" for integers (1234567 $\rightarrow$ "1,234,567") or f"{price:,.2f}" for floating-point numbers with fixed decimal places (1234567.89 $\rightarrow$ "1,234,567.89")—which inserts ASCII commas every three digits without needing external libraries or OS locale changes (and swap , for _ via f"{num:_}" when underscore separators are preferred).

Basic Example

population = 241_499_431
revenue = 1849250.5

# 1. Recommended: Integer with comma thousands separators
print(f"{population:,}")
# Output: 241,499,431

# 2. Float with comma thousands separators AND 2 decimal places:
print(f"${revenue:,.2f}")
# Output: $1,849,250.50

# 3. Fixed column width + right-aligned + comma thousands separators:
print(f"|{revenue:15,.2f}|")
# Output: |   1,849,250.50|

# 4. Underscore thousands separator (Python 3.6+):
print(f"{population:_}")
# Output: 241_499_431

Key Details & Edge Cases

  • Order of flags inside the format specification mini-language ([[fill]align][sign][z][#][0][width][grouping_option][.precision][type]):
    • The comma grouping option must come before .precision (f"{val:,.2f}"), never after (f"{val:.2,f}" raises ValueError: Invalid format specifier).
    • Similarly, sign-aware zero-padding 0 works with commas (f"{1234:08,}" $\rightarrow$ "0,001,234"), keeping commas aligned inside zero-padded fields.
  • Standalone formatting without surrounding string literals (format(num, ",")):
    • If you only need the formatted string itself without extra text, format(1234567, ",") (or format(1234567.89, ",.2f")) avoids wrapping the value in an f-string.
  • Locale-specific separators (1.234.567,89 in Europe or Indian/Pakistani 24,14,99,431):
    • f"{num:,}" always uses US/UK style 3-digit comma grouping and a . decimal point regardless of system locale.
    • For German/French/Spanish formatting (1.234.567,89), use f"{num:n}" after setting locale.setlocale(locale.LC_ALL, "de_DE.UTF-8"), or use babel.numbers.format_decimal(num, locale="ur_PK") / locale="en_IN" (pip install Babel) for thread-safe South Asian lakh/crore grouping (24,14,99,431) without mutating global process locale state.
  • Parsing comma-formatted strings back into int or float:
    • Python’s built-in int("1,234") and float("1,234.50") raise ValueError on commas—strip commas first via int(s.replace(",", "")) or float(s.replace(",", "")) (or pass thousands="," to pd.read_csv(..., thousands=",") when loading CSV columns).
  • Formatting NumPy arrays or Pandas DataFrames with commas:
    • Format whole Pandas columns for display via df.style.format({"revenue": "${:,.2f}"}) or pd.options.display.float_format = "{:,.2f}".format (keep underlying DataFrame columns numeric until display/export so arithmetic still works).

Comparison of Thousands-Separator Formatting Methods in Python

Method Syntax Example Grouping Style Thread-Safe? Best Used When
f-String :, Specifier (Recommended) f"{val:,.2f}" Fixed 3-digit ASCII commas + . decimal (1,234,567.89) Yes Standard CLI output, reports, logs, and web/API formatting in Python 3.6+.
Built-in format() Function format(val, ",.2f") Fixed 3-digit ASCII commas + . decimal Yes Passing a formatter function (e.g., map(lambda x: format(x, ","), nums)).
str.format() Method "{:,.2f}".format(val) Fixed 3-digit ASCII commas + . decimal Yes Reusable format templates stored in external strings or config files.
locale.format_string(..., grouping=True) / f"{val:n}" f"{val:n}" (after locale.setlocale) OS locale rules (e.g., 1.234.567,89) No (setlocale mutates process-wide state) Desktop/CLI apps adapting to the user’s configured OS regional settings.
babel.numbers.format_decimal (pip install Babel) format_decimal(val, locale="en_IN") Any regional grouping (24,14,99,431 or 1.234.567,89) Yes (per-call locale= argument) Multi-user web apps needing Indian/Pakistani lakh-crore or European separators safely.