Print number with comma as thousands separator in Python

avatar

Borislav Hadzhiev

Last updated: Sep 2, 2022

banner

Photo from Unsplash

Print number with comma as the thousands separator in Python #

Use a formatted string literal to print a number with a comma as the thousands separator, e.g. print(f'{my_integer:,}'). You can use an expression in the f-string to format the number with a comma as the thousands separator and print the result.

main.py
my_integer = 456789123 # ✅ Print integer with comma as thousands separator result = f'{my_integer:,}' print(result) # 👉️ 456,789,123 # --------------------------------- # ✅ Print float with comma as thousands separator rounded to 2 decimal places my_float = 456789.456789 result = f'{my_float:,.2f}' print(result) # 👉️ 456,789.46

We used a formatted string literal to print a number with a comma as the thousands separator.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'The number is:' my_int = 123456 result = f'{my_str} {my_int}' print(result) # 👉️ The number is: 123456

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format-specific mini-language in expression blocks.

main.py
my_integer = 456789123 print(f'{my_integer:,}') # 👉️ 456,789,123

The comma after the colon is the thousands separator.

You can use the same approach to print a floating-point number with a comma as the thousands separator, rounded to N decimal places.

main.py
my_float = 456789.456789 result = f'{my_float:,.2f}' print(result) # 👉️ 456,789.46 result = f'{my_float:,.3f}' print(result) # 👉️ 456,789.457
The comma after the colon is the thousands separator and the digit after the period is the number of decimal places the float should have.

If you have the number of decimal places stored in a variable, wrap it in curly braces in the f-string.

main.py
my_float = 456789.456789 number_of_decimals = 2 result = f'{my_float:,.{number_of_decimals}f}' print(result) # 👉️ 456,789.46

If you need to format a list of numbers with a comma as the thousands separator, use a list comprehension.

main.py
list_of_numbers = [456789, 234567, 123456] result = [f'{item:,}' for item in list_of_numbers] print(result) # 👉️ ['456,789', '234,567', '123,456']

We used a list comprehension to iterate over the list of floating-point numbers.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to format the current number with a comma as the thousands separator and return the result.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.