insert thousands separators

Steven Taschuk staschuk at telusplanet.net
Fri Jun 13 14:38:42 EDT 2003


Quoth Nick Vargish:
  [...]
> 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)

A wee bug:

    >>> commafy(1001)
    '1,1'

I believe

    return val < 0 and '-' + commafy(abs(val)) \
        or val < 1000 and str(val) \
        or commafy(val / 1000) + ',' + '%03d' % (val % 1000)

is correct.

Avoiding recursion seems reasonable, though:

    def digits(value, base=10):
        value = abs(value)
        d = []
        while True:
            value, r = divmod(value, base)
            d.append(r)
            if not value:
                break
        d.reverse()
        return d

    def commafy(val):
        d = digits(val, 1000)
        d[0] = str(d[0])
        if val < 0:
            d[0] = '-' + d[0]
        for i in range(1, len(d)):
            d[i] = '%03d' % d[i]
        return ','.join(d)

  [...]
-- 
Steven Taschuk                                                 o- @
staschuk at telusplanet.net                                      7O   )
                                                               "  (





More information about the Python-list mailing list