Explain Codes LogoExplain Codes Logo

How to print a number using commas as thousands separators

python
functions
best-practices
performance
Nikita BarsukovbyNikita Barsukov·Sep 26, 2024
TLDR

The simplest way to add commas to numbers in Python using f-string formatting with :, :

print(f"{1234567:,}")

Outputs: 1,234,567

Adapting to different Python versions

Different Python versions may require different formatting approaches:

For Python 2.7 through 3.5, you can use the format() method:

print("{:,}".format(1000000)) # It's like a party, but the guests are commas!

Outputs: 1,000,000

For versions prior to Python 3.6, you can use the format() function directly:

print(format(1234567, ",")) # Remember, you "comma" here often!

Outputs: 1,234,567

Leveraging built-in formatting capabilities

Python offers some sophisticated built-in formatting methods that you might find useful:

Taking locale into account

Sometimes, you need to respect local customs, even in programming!

import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') print(locale.format_string("%d", 1000000, grouping=True)) # Print money the American way!

Outputs: 1,000,000

Developer-friendly formatting with underscores

Spice it up with some underscores for the ultimate developer swag:

print(f"{0b1010101010:_b}") # Because who needs commas when you got underscores!

Outputs: 10_1010_1010

Tailoring a custom function

When the built-in methods seem too mainstream for you, go custom with intWithCommas.

Introducing the intWithCommas function

def intWithCommas(x): if x < 0: return '-' + intWithCommas(-x) result = str(x) while len(result) > 3: result = f"{result[:-3]},{result[-3:]}" # Hand-picked, artisanal commas at just the right spots! return result print(intWithCommas(1000000))

Outputs: 1,000,000

Solving tricky scenarios

Getting the commas right sometimes needs a little more care:

Handling negatives like a boss

Negatives got you down? With Python, you can flip them around!

formatted_number = intWithCommas(-1234567).replace("-", "–") # Minus, meet comma. You two play nice!

Keeping performance in check

Your program's not a speedster? Let's streamline it!

# Not recommended #print(','.join(str(1000000)[i:i+3] for i in range(0, len(str(1000000)), 3))) # Way too many loo-loops for a simple comma! # Clear and maintainable print(intWithCommas(1000000)) # Oldie but a Goldie!