How to print a number using commas as thousands separators
The simplest way to add commas to numbers in Python using f-string formatting with :,
:
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:
Outputs: 1,000,000
For versions prior to Python 3.6, you can use the format()
function directly:
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!
Outputs: 1,000,000
Developer-friendly formatting with underscores
Spice it up with some underscores for the ultimate developer swag:
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
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!
Keeping performance in check
Your program's not a speedster? Let's streamline it!
Was this article helpful?