insert thousands separators

Dan Bishop danb_83 at yahoo.com
Fri Jun 13 20:14:41 EDT 2003


Nick Vargish <nav at adams.patriot.net> wrote in message news:<yyyvfv9hpj9.fsf at adams.patriot.net>...
> Marcus Bergmann <marcus.bergmann at isst.fhg.de> writes:
> 
> > how can I insert thousands separators into an integer or a string,
> > e.g. 1000000 to 1.000.000?
> 
> You may need to modify the following to match the "integer or string"
> part of your request. commafy() here accepts and integer but returns a
> string...
[snip]
> def commafy(val):
>    """Returns a string version of val with commas every thousandth
>    place."""
>    return val < 0 and '-' + commafy(abs(val)) \
>           or val < 1000 and str(val) \
>           or commafy(val / 1000) + ',' + commafy(val % 1000)
[test function snipped]

Your testing wasn't thorough enough.

>>> commafy(12034)
'12,34'
>>> commafy(1000000)
1,0,0

Also, if Python is run with "-Qnew",

>>> commafy(1234)
1.234,234

Try this instead:

def groupThousands(val, sep=','):
   if val < 0:
      return '-' + groupThousands(-val, sep)
   if val < 1000:
      return str(val)
   return '%s%s%03d' % (groupThousands(val // 1000, sep), sep, val % 1000)




More information about the Python-list mailing list