How do I print an integer with commas as thousands separators?
1234567 ⟶ 1,234,567
It does not need to be locale-specific to decide between periods and commas.
_
as the thousand separatorf'{value:_}' # For Python ≥3.6
Note that this will NOT format in the user's current locale and will always use _
as the thousand separator, so for example:
1234567 ⟶ 1_234_567
,
as the thousand separator'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
Per Format Specification Mini-Language,
The
','
option signals the use of a comma for a thousands separator. For a locale aware separator, use the'n'
integer presentation type instead.
and:
The
'_'
option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type'd'
. For integer presentation types'b'
,'o'
,'x'
, and'X'
, underscores will be inserted every 4 digits.