A suggestion for a possible Python module

Jp Calderone exarkun at intarweb.us
Sun Mar 9 04:57:16 CET 2003


On Sat, Mar 08, 2003 at 07:00:55PM -0800, Matt Gerrans wrote:
> "Andrew Dalke" wrote:
> > ...
> > The ones I could think of are:
> >   - insert commas in a number, as in "10000" -> "10,000"
> >
> >   def commafy(s):
> >     s = s.reverse()
> >     terms = []
> >     for i in range(0, len(s), 3):
> >       terms.append(s[i:i+3])
> >     return ",".join(terms).reverse()
> > ...
> 
> For this one, I'd prefer locale.format().
> 

  This is the most common alternative solution I hear, and I don't think
it's right.

  locale.format() isn't guaranteed to put in commas.  (You can argue that
you should respect the locale's conventions and accept this, but that's a
different discussion).

  You could, of course, -change- the locale, then change it back afterwards,
but hopefully everyone sees that for the dirty hack it is.  FWIW:

    def commaize(s):
        P = len(s) % 3
        st = s[:P] + (len(s) > 3 and P and ',' or '')
        return st + ','.join([s[i:i+3] for i in range(P, len(s), 3)])

  It's only two lines shorter, but it doesn't involve going through the
string backwards ;)

  Jp

-- 
Seduced, shaggy Samson snored.
She scissored short.  Sorely shorn,
Soon shackled slave, Samson sighed,
Silently scheming,
Sightlessly seeking
Some savage, spectacular suicide.
                -- Stanislaw Lem, "Cyberiad"
-- 
 up 5 days, 19:59, 7 users, load average: 0.00, 0.02, 0.00





More information about the Python-list mailing list