Formatting question : printing numbers with thousands separators ?

Christian Tanzer tanzer at swing.co.at
Fri Aug 31 12:41:52 EDT 2001


skip at pobox.com (Skip Montanaro) wrote:

>     Fred> how do I print 246814345 as 246,814,345 (or 246 814 345) ?
> 
> I'm sure there are more clever ways, but this seems to work:
> 
>     def separate(n, sep=','):
>         ln = list(str(n))
>         ln.reverse()
>         newn = []
>         while len(ln) > 3:
>             newn.extend(ln[:3])
>             newn.append(sep)
>             ln = ln[3:]
>         newn.extend(ln)
>         newn.reverse()
>         return "".join(newn)
> 
>     >>> separate("2342342342344567")
>     '2,342,342,342,344,567'
>     >>> separate("2342342342344567", sep=' ')
>     '2 342 342 342 344 567'
>     >>> separate(5)
>     '5'
>     >>> separate(35)
>     '35'
>     >>> separate(235)
>     '235'
>     >>> separate(1235)
>     '1,235'
>     >>> separate(1235, ' ')
>     '1 235'

How about:

>>> import re
>>> sep_1000_pat = re.compile("(\d{1,3}) (?= (?: \d\d\d)+ (?! \d) )", re.X)
>>> sep_1000_pat.sub(r"\g<1>,", "2342342342344567")
'2,342,342,342,344,567'

Short, but then you need Friedl's masterpiece on regular expression to
understand it...

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list