How can I print a number with commas as thousands separators in Python?
For example, I want to convert the integer 1234567 into 1,234,567. It does not need to be locale-specific, meaning I just want to use commas as the separator, not considering periods or other locale-specific formatting rules.
If you’re looking for a straightforward and commonly used approach, the format()
method is perfect for this. It’s built right into Python and gets the job done neatly. Here’s how you can use it:
number = 1234567
print("{:,}".format(number))
This will output:
1,234,567
It’s simple and works well for most scenarios when you need to python format number with commas.
Building on Ambika’s answer, if you’re using Python 3.6 or later, f-strings are an even more concise and modern way to achieve this. Here’s how you can do it:
number = 1234567
print(f"{number:,}")
This will also output:
1,234,567
F-strings are incredibly handy and are becoming the go-to choice for many Python developers for tasks like python format number with commas because they keep the code clean and readable.
If you’re looking for more advanced options or foresee scenarios where you might want additional control, you could consider using the locale
module. While you mentioned locale-specific formatting isn’t necessary, this method can still be tailored to your needs:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Setting locale to US
number = 1234567
print(locale.format_string("%d", number, grouping=True))
The output is:
1,234,567
This approach allows you to handle broader formatting cases in addition to python format number with commas, making it versatile for global applications if needed.