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

Richard Bow donkan7 at yahoo.com
Wed Oct 16 16:37:48 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?

Thanks,

Richard Bow




More information about the Python-list mailing list