How to print an integer with commas; E.g., 3,056,789

Paul Simmonds psimmo60 at hotmail.com
Wed Oct 16 16:55:53 CEST 2002


>John Arundel <john at splange.freeserve.co.uk> wrote in
>news:mailman.1034773342.23488.python-list at python.org:
>
> > How about:
> >
> > def commaise(seq):
> >     if len(seq) <= 3:
> >         return seq
> >     else:
> >         return "".join(commaise(seq[:-3]) + ',' + seq[-3:])
> >
> >>>> commaise("3056789")
> > '3,056,789'
>
>I see that this works well, but I don't understand it. I _think_ I
>understand join(), but how is the looping accomplished? I suspect the "" in
>the same line is what does this, but could you or someone explain a bit?

It works by calling itself:   ||
                              \/
> >         return "".join(commaise(seq[:-3]) + ',' + seq[-3:])

So it runs the same function on the [:-3] slice, until it hits a slice 
smaller than or equal to 3 digits long. Hell of a lot neater doing this by 
recursion. Thanks John.

HTH,
Paul

_________________________________________________________________
Surf the Web without missing calls! Get MSN Broadband. 
http://resourcecenter.msn.com/access/plans/freeactivation.asp





More information about the Python-list mailing list