How to print an integer with commas; E.g., 3,056,789
John Arundel
john at splange.freeserve.co.uk
Wed Oct 16 08:53:38 EDT 2002
On 2002-10-16 at 08:06:33, Padraig Brady warbled:
> >Given any integer n, how can I convert str(n) to a string with commas in
> >the appropriate places? For example, if n is 3056789, I'd like to convert
> >str(3056789) to "3,056,789", for better readability of output.
>
> Yes wouldn't it be nice to have:
>
> >>> i=3056789
> >>> print "%h %.2m %.2M %.2k %.2K" % i, i, i, i, i
> 3,056,789 3.06M 2.92Mi 3056.79K 2985.15Ki
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 was an only child... eventually."
- Steven Wright
---------------------------------------------------------------------
I prefer encrypted mail - http://www.splange.freeserve.co.uk/pgp.html
---------------------------------------------------------------------
More information about the Python-list
mailing list