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

John Arundel john at splange.freeserve.co.uk
Thu Oct 17 05:36:03 EDT 2002


On 2002-10-16 at 09:26:01, I warbled:
> def commaise(seq):
>     if len(seq) <= 3:
>         return seq
>     else:
>         return "".join(commaise(seq[:-3]) + ',' + seq[-3:])
>
> >>> commaise("3056789")
> '3,056,789'

Just to close the book on this one, my colleagues managed to come up
with the following suggestions:

Using a list comprehension:

''.join([ seq[i] + ((not((len(seq)-i-1)%3) and ',')or'') for i in
range(len(seq)) ])[:-1]

Using regular expressions:

re.sub(r'(\d*?)(?=(\d\d\d)+$)',r'\1,',str(seq))

Interestingly, the recursive solution is also the fastest. The list
comprehension is marginally slower, while the regex solution is about
three times slower than either of these. I find the recursive method the
easiest to read, so it's nice that this solution should be the
fastest :)

this-would-make-a-good-interview-question-ly yrs,
John

--
"This life is a test. It is only a test. Had this been an actual
life, you would have received further instructions as to what to do
and where to go."                                           - Unknown
---------------------------------------------------------------------
I prefer encrypted mail - http://www.splange.freeserve.co.uk/pgp.html
---------------------------------------------------------------------




More information about the Python-list mailing list