simplify printing of a list

beliavsky at aol.com beliavsky at aol.com
Thu Jun 3 18:08:57 EDT 2004


To print a list with a specified format one can write (for example)

for j in [0,1,2]:
    print "%6d"%j,
print

The code

print "%6d"%[0,1,2]

currently produces a syntax error, but it would be convenient if it
had the same meaning as the loop above.

One can write a function to print a list, for example

def print_list(x,fmt_x="%6d"):
    """ print a list on one line """
    for y in x: print fmt_x % y,

print_list([0,1,2])

but it gets messy to print several lists on the same line.

In Fortran 90/95 one can write 

print "(100i6)",(/0,1,2/)

where the format (100i6) means that UP TO 100 integers are printed
using 6 columns. An alternative suggestion I have for Python is to
allow

print "100%6d"%[0,1,2]

with the same meaning.

I realize that what I am asking for is just a convenience, but it is
one that I could use in almost every program I write.



More information about the Python-list mailing list