Python Add Comma Into Number String

In Python 2.7 and 3.x, you can use the format syntax :,

>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00

This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"


if you are using Python 3 or above, here is an easier way to insert a comma:

First way

value = -12345672
print (format (value, ',d'))

or another way

value = -12345672
print ('{:,}'.format(value)) 

You could use locale.currency if TotalAmount represents money. It works on Python <2.7 too:

>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'

Note: it doesn't work with the C locale so you should set some other locale before calling it.

Tags:

Python

String