Formatting question : printing numbers with thousands separators ?

June Kim juneaftn at orgio.net
Fri Aug 31 13:33:11 EDT 2001


I suppose the numbers to be general, such as w/w.o. point and plus/minus sign.

* The most obvious and simplest way is:

>>> locale.setlocale(locale.LC_ALL,"")
>>> locale.format("%s",-345.6789,1)
'-345.6789'

* and if there's some problem setting the locale in the platform:

>>> def _temp(lc=locale.localeconv()):
        lc.update({'thousands_sep':',','grouping':[3,3,0]})
        return lc

>>> locale.localeconv=_temp
>>> locale.format("%s",12345,1)
'12,345'

* and the most(or more or less) obfuscated way as a one-liner is:

def sep(s):  return
re.sub(r"([-+]?\d{1,3}(\.\d*)?)(?=(\d{3})*(\.|$))",r",\1",s)[1:]

* and the most elegant way is:

def sep(s):
    p=s.find('.')
    if p==-1: p=len(s)
    for i in range(p-3,s[0] in ('+','-'),-3):
        s=s[:i]+','+s[i:]
    return s

Best wishes,

June


----- Original Message -----
From: "Fred Pacquier" <fredp at mygale.org.nospam>
Newsgroups: comp.lang.python
Sent: Friday, August 31, 2001 8:33 PM
Subject: Formatting question : printing numbers with thousands separators ?


>
> Sorry if this is a really dumb question, but I believe I did my homework
> (docs, FATS, Google etc.) and the answer still eludes me :
>
> how do I print 246814345 as 246,814,345 (or 246 814 345) ?
>
> TIA,
> fp
>
> --
> YAFAP : http://www.multimania.com/fredp/



More information about the Python-list mailing list