Home > python > Pretty print an integer

## Pretty print an integer

Exercise: Take an integer and print it in a pretty way, i.e. use commas as thousands separators. Example: 1977 should be 1,977.

Solution:

```#!/usr/bin/env python

def numberToPrettyString(n):
"""Converts a number to a nicely formatted string.
Example: 6874 => '6,874'."""
l = []
for i, c in enumerate(str(n)[::-1]):
if i%3==0 and i!=0:
l += ','
l += c
return "".join(l[::-1])
#

if __name__ == "__main__":
number = 6874
print numberToPrettyString(number)   # '6,874'
```

The idea is simple. Consider the number `1977`. Convert it to string (`"1977"`) and reverse it (`"7791"`). Start processing it from left to right and after every third character add a comma: `"7"` -> `"77"` -> `"779,"` (comma added) -> `"779,1"`. Now reverse the string (`"1,977"`). Done.

Update (20131125)
There is an easier way. You can do it with string formatting too:

```>>> n = 1977
>>> "{:,}".format(n)
'1,977'
```

Thanks to Krisztián B. for the tip.

Categories: python Tags: , , ,
1. July 1, 2014 at 21:35

This should work on older Python versions:

```>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'
```

http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x

• July 1, 2014 at 22:00

Thanks. There is also a nice module that can do it: humanize (https://github.com/jmoiron/humanize). Example:

```>>> import humanize
>>> humanize.intcomma(12345)
'12,345'
```