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

Richard Bow donkan7 at yahoo.com
Wed Oct 16 10:17:41 EDT 2002


"Paul Simmonds" <psimmo60 at hotmail.com> wrote in 
news:mailman.1034770761.2768.python-list at python.org:

> 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

Thanks very much to all for the advice. Before I got back here to read it, 
and instead of going to bed, I remembered slices and came up with this 
script, which I want to turn into a function, but don't know how yet.

======================================
n = raw_input("Enter a non-negative integer: ")

n = long(n)
print "n = ", n
s = str(n)
sub = ""

if n < 1000:
    print "No commas needed"
else:
    for k in range(len(s)):

        if k > 0 and k % 3 == 0:
            char = ","
            sub = char + sub

        char = s[-k - 1]
        sub = char + sub

    print "n with commas is", sub
==============================

Seems to work, but can the code be improved?

Thanks again,

Richard Bow




More information about the Python-list mailing list