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}"raisesValueError: Invalid format specifier). - Similarly, sign-aware zero-padding
0works with commas (f"{1234:08,}"$\rightarrow$"0,001,234"), keeping commas aligned inside zero-padded fields.
- The comma grouping option must come before
- Standalone formatting without surrounding string literals (
format(num, ",")):- If you only need the formatted string itself without extra text,
format(1234567, ",")(orformat(1234567.89, ",.2f")) avoids wrapping the value in an f-string.
- If you only need the formatted string itself without extra text,
- Locale-specific separators (
1.234.567,89in Europe or Indian/Pakistani24,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), usef"{num:n}"after settinglocale.setlocale(locale.LC_ALL, "de_DE.UTF-8"), or usebabel.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
intorfloat:- Python’s built-in
int("1,234")andfloat("1,234.50")raiseValueErroron commas—strip commas first viaint(s.replace(",", ""))orfloat(s.replace(",", ""))(or passthousands=","topd.read_csv(..., thousands=",")when loading CSV columns).
- Python’s built-in
- Formatting NumPy arrays or Pandas DataFrames with commas:
- Format whole Pandas columns for display via
df.style.format({"revenue": "${:,.2f}"})orpd.options.display.float_format = "{:,.2f}".format(keep underlying DataFrame columns numeric until display/export so arithmetic still works).
- Format whole Pandas columns for display via
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. |
You must log in or register to comment.
