insert thousands separators

Bengt Richter bokr at oz.net
Fri Jun 13 21:35:42 EDT 2003


On Fri, 13 Jun 2003 12:38:42 -0600, Steven Taschuk <staschuk at telusplanet.net> wrote:

>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.
Oops. That's embarassing ;-/ Sorry Nick, I did that just interactively,
and didn't test very well, I'm afraid. I guess I would do that corrections as

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


>
>Avoiding recursion seems reasonable, though:
Sure, there were a number of variations. I just wanted to throw in something
different, and was too hasty.
>
>    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)
>
>  [...]

Yet another non-recursive variant (not extensively tested ;-/ ):

def commafy(val):
    sign, val, rest = '-'[:val<0], str(abs(val)), []
    while val: val, rest = val[:-3], ([val[-3:]] + rest)
    return sign + ','.join(rest)

or possibly

def commafy(val):
    sign, val, rest = '-'[:val<0], str(abs(val)), ''
    while val: val, rest = val[:-3], '%s,%s'%(val[-3:], rest)
    return sign + rest[:-1]
 
Regards,
Bengt Richter




More information about the Python-list mailing list