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

Paul Simmonds psimmo60 at hotmail.com
Wed Oct 16 08:18:09 EDT 2002


Richard Bow wrote:
<snip>
>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.
<snip>

I don't think there's a function available for this, but it's fairly easy to 
roll your own- just use slices of the string:

def comma(bigint):
    strint=str(bigint)
    i=0              #increment counter
    j=len(strint)%3  #number of chars @ beginning
    newstr=strint[0:j]
    while i<len(strint)/3:
	newstr=newstr+','+strint[(3*i)+j:(3*(i+1))+j]
	i=i+1
    return newstr

For example, given an int 1234567, this function will return a string 
"1,234,567". There's probably a neater way working from the backend of 
strint using negative slice indexing, but you get the idea.
HTH,
Paul

**********************************************
I used to have a handle on life, but it broke.
**********************************************


_________________________________________________________________
Unlimited Internet access -- and 2 months free!  Try MSN. 
http://resourcecenter.msn.com/access/plans/2monthsfree.asp





More information about the Python-list mailing list