Thousands Separator in Python
Question: > **Possible Duplicate:**  
>  [how to print number with commas as thousands separators in Python
> 2.x](http://stackoverflow.com/questions/1823058/how-to-print-number-with-
> commas-as-thousands-separators-in-python-2-x)

Does anyone know of an easier way to make numbers have thousands separation
than this:

    
    
    def addComma(num):
        (num, post) = str(num).split('.')
        num = list(num)
        num.reverse()
    
        count = 0
        list1 = []
    
        for i in num:
            count += 1
            if count % 3 == 0:
                list1.append(i)
                list1.append(',')
            else:
                list1.append(i)
    
        list1.reverse()
    
        return ''.join(list1).strip(',') + '.' + post
    

It works, but it seems REALLY fragile...


Answer: Use `locale.format()` with `grouping=True`

    
    
    >>> import locale
    >>> locale.setlocale(locale.LC_NUMERIC, 'en_US')
    'en_US'
    >>> locale.format("%d", 1234567, grouping=True)
    '1,234,456'
    

See <http://docs.python.org/library/locale.html#locale.format> for more
information.

