In Python, there are two easy ways to format large numbers with commas as separators to improve the readability of information (when printing to the console or displaying on the web).
Table Of Contents
Using f-strings (Python 3.6+)
Just enclose your number in a pair of curly braces {}
within an f-strings, then use a comma as the format specifier.
Example:
number = 12345678901234567
# Format the number with comma separators
formatted_number = f'{number:,}'
print(formatted_number)
Output:
12,345,678,901,234,567
Note that formatted_number
is a string.
Using the format() function
Pass your number as the first argument and pass a comma as the second argument to the format()
function, and you will get the desired result.
Example:
number = 10000000000000000
# Format the number with comma separators
formatted_number = format(number, ',')
print(formatted_number)
Output:
10,000,000,000,000,000
That’s it. Happy coding!