Presenting numbers clearly, especially large ones, often involves using thousands separators (like commas or spaces) and formatting them as currency.
This guide explores various methods in Python to format numbers with thousands separators and as currency, using f-strings, str.format(), and the locale module.
Formatting Numbers with Thousands Separators
Using f-strings (Recommended)
f-strings provide the most concise and readable way to add a comma as a thousands separator:
my_int = 489985123
result = f'{my_int:,}'
print(result) # Output: 489,985,123- The comma (
,) after the colon (:) in the f-string format specifier tells Python to use a comma as the thousands separator.
Using str.format()
The str.format() method offers an alternative:
my_int = 489985123
result = '{:,}'.format(my_int)
print(result) # Output: 489,985,123Using the locale Module (Locale-Aware)
For formatting based on the user's system locale (which might use different separators like periods), use the locale module and the :n format specifier:
import locale
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except locale.Error:
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error:
print("Warning: Could not set a suitable locale. Using default C locale.")
locale.setlocale(locale.LC_ALL, 'C') # Fallback to basic C locale
my_int = 489985123
result = f'{my_int:n}'
print(result)locale.setlocale(locale.LC_ALL, '')sets the locale based on the system's environment variables.- The
:nformat specifier tells Python to use the locale-specific thousands separator.
Using Spaces as Separators
To use spaces instead of commas, replace the comma after formatting:
my_int = 489985123
result_fstring = f'{my_int:,}'.replace(',', ' ')
print(result_fstring) # Output: 489 985 123
import locale
locale.setlocale(locale.LC_ALL, '') # Set locale first
result_locale = f'{my_int:n}'
separator = locale.localeconv().get('thousands_sep', ',') # Get locale separator
result_locale_space = result_locale.replace(separator, ' ')
print(result_locale_space) # Output might be: 489 985 123Formatting Floats with Thousands Separators and Decimals
Combine the comma separator with precision formatting for floats:
my_float = 489985.456789
result_2dp = f'{my_float:,.2f}'
print(result_2dp) # Output: 489,985.46
result_3dp = f'{my_float:,.3f}'
print(result_3dp) # Output: 489,985.457- The
,enables the thousands separator. .Nfrounds the float toNdecimal places.
Formatting Lists of Numbers with Thousands Separators
Use list comprehensions to format all numbers in a list.
Formatting Lists of Integers
my_list = [489985123, 123456789, 23456789, 45678901]
formatted_list = [f'{x:,}' for x in my_list]
print(formatted_list)Formatting Lists of Floats
list_of_floats = [489985.456789, 123456.678123, 234567.12345]
formatted_list = [f'{item:,.2f}' for item in list_of_floats]
print(formatted_list)Formatting Numbers as Currency
Using f-strings
Prepend the currency symbol and use standard number formatting:
my_float = 15467.3
result = f'${my_float:,.2f}' # Add $ sign, comma separator, 2 decimal places
print(result) # Output: $15,467.30
result_no_comma = f'${my_float:.2f}'
print(result_no_comma) # Output: $15467.30Using locale.currency() (Locale-Aware)
The locale.currency() function provides locale-aware currency formatting:
import locale
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except locale.Error:
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error:
print("Warning: Could not set locale. Currency formatting might be basic.")
locale.setlocale(locale.LC_ALL, 'C')
my_float = 15467.3
result_grouped = locale.currency(my_float, grouping=True) # With grouping (e.g., commas)
print(result_grouped) # Output (depends on locale): $15,467.30
result_nogroup = locale.currency(my_float, grouping=False) # Without grouping
print(result_nogroup) # Output (depends on locale): $15467.30
result_nosymbol = locale.currency(my_float, grouping=True, symbol=False) # Without currency symbol
print(result_nosymbol) # Output (depends on locale): 15,467.30locale.currency()uses the current locale settings to format the number, including the correct currency symbol and separators.- The
grouping=Trueargument enables the thousands separator according to the locale. - The
symbol=True(default) includes the locale's currency symbol.