Pretty Integers

Carsten Gaebler clpy at snakefarm.org
Fri Mar 15 17:40:22 EST 2002


Lindstrom Greg - glinds wrote:
> 
> I would like to add commas to the integers I am writing (for example:
> 12345678 --> 12,345,678).  I have a fairly ugly method that relies heavily
> upon mods, but am convinced there must be a "pretty" way to do it.  How
> would you go about this task?
> 

How about some nice recursion? This is how I do it:

#! /usr/bin/python

def pretty_int(ugly_int):
    if len(ugly_int) <= 3:
        return ugly_int
    return pretty_int(ugly_int[:-3]) + "," + ugly_int[-3:]

ugly_int = 12345678
print pretty_int(str(ugly_int))


cg.



More information about the Python-list mailing list