[Tutor] more newbie questions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 30 Apr 2002 13:55:47 -0700 (PDT)


On Tue, 30 Apr 2002, Lloyd Kvam wrote:

>  >>> for row in grid:
> ... 	print "%s%s%s" % tuple(row)
> ...
> 123
> 456
> 789
>
> Then I had a brain storm for when you don't know the size of the
> row:
>  >>> for row in grid:
> ... 	fmt = "%s" * len(row)
> ... 	print fmt % tuple(row)
> ...
> 123
> 456
> 789


Here's an alternative way of doing it, but it needs a little more care:

###
>>> def printgrid(grid):
...     for row in grid:
...         stringed_row = map(str, row)
...         print ''.join(stringed_row)
...
>>> grid = [[1, 2, 3],
...         [4, 5, 6],
...         [7, 8, 9]]
>>>
>>> printgrid(grid)
123
456
789
###

One part of the printgrid() definition might seem a little weird, so it
might be good to mention it. The reason why printGrid() does a
'map(str, row)' thing right before the joining is because string
joining assumes that it's joining a list of strings:

###
>>> print ''.join(['one', 'two', 'three'])
onetwothree
>>>
>>> print ''.join([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
###

and trying to string.join() a list of numbers will result in a TypeError,
warning us that we're doing something potentially suspicious.

The map() is there to apply the str()ing function on every element of row,
and collects all those results into stringed_row, so that the
string.join() can work.