A suggestion for a possible Python module

Matt Gerrans mgerrans at mindspring.com
Sun Mar 9 22:38:34 CET 2003


> > For this one, I'd prefer locale.format().
>
> Jp Calderone
> > This is the most common alternative solution I hear, and I don't
> > think it's right.
>
> I agree.  My spec was to put commas into numbers, with an
> example which implied it was using the US convention.  Eg, it could
> be that the input goes to a program which isn't format aware, so
> it *must* be in that form.

Yes, I must admit, I have a little commas-adding module I often use that has
one method which uses locale and the other which looks like this:

def AddCommas(x):
   """
   Returns x in the form of a string, with comma formatting.
   eg: 123456789 -> 123,456,789
   This is my old implementation (commas(), which uses the locale module is
   the new fangled technology), which figures out where to put the commas
the
   hard way.
   """
   if type(x) != type(0L):
      x = long(x)

   if abs(x) < 1000:
      return "%d" % x

   chunks = []
   neg = 0
   if x < 0:
      neg = 1
      x = -x

   while x > 999:
      chunks.append( x - (x / 1000) * 1000 )
      x = x / 1000

   chunks.append(x)
   chunks.reverse()

   if neg:
      s = "-%d" % chunks[0]
   else:
      s = "%d" % chunks[0]

   for i in chunks[1:]:
      s = s + ",%03d" % i
   return s

I guess it needs to be enhanced for floating point values...

- Matt






More information about the Python-list mailing list