simplify printing of a list
Peter Otten
__peter__ at web.de
Fri Jun 4 04:46:52 EDT 2004
beliavsky at aol.com wrote:
> 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.
A TypeError. What if I wanted the current behaviour, e. g
>>> "%s" % [1, 2, 3]
'[1, 2, 3]'
instead of
>>> "%s" % [1, 2, 3]
'1 2 3' #faked
>
> 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.
How about different operators for the two formatting operations:
>>> class Format(str):
... def __mul__(self, other):
... return " ".join(map(self.__mod__, other))
...
>>>
>>> Format("%6d") % 1
' 1'
>>> Format("%6d") * [1, 2, 3]
' 1 2 3'
>>>
Peter
More information about the Python-list
mailing list