pythonnumber-formatting

How to print a number using commas as thousands separators


How do I print an integer with commas as thousands separators?

1234567   ⟶   1,234,567

It does not need to be locale-specific to decide between periods and commas.


Solution

  • Locale-agnostic: use _ as the thousand separator

    f'{value:_}'          # For Python ≥3.6
    

    English style: use , as the thousand separator

    '{:,}'.format(value)  # For Python ≥2.7
    f'{value:,}'          # For Python ≥3.6
    

    Locale-aware

    import locale
    locale.setlocale(locale.LC_ALL, '')  # Use '' for auto, or force e.g. to 'en_US.UTF-8'
    
    '{:n}'.format(value)  # For Python ≥2.7
    f'{value:n}'          # For Python ≥3.6
    

    Reference

    Per Format Specification Mini-Language,

    The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

    and:

    The '_' option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits.