[Tutor] printing columns

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Fri, 21 Jul 2000 13:51:39 -0700 (PDT)

On Thu, 20 Jul 2000, Ben Beuchler wrote:

> I have a list of around 650 or so items.  I would like to be able to
> print them in columns, three across, like so:
> item1		item2		item3
> item4		item5		item6
> item7		item8		item9
> Any suggestions on a clean way to accomplish this?  The items will be of
> varying width, so just adding tabs won't reliably format them.

It sounds like you might want a function to pad a string to a fixed width.  
Other people have suggested using:

  print "%10s%10s%10s" % (item[i], item[i+1], item[i+2])

which will work well.  It will, however, be padded with spaces to the
left, where we actually want padding on the right.  For example:

>>> print "%10s%10s%10s" % ('hello', 'world', 'test')
     hello     world      test

If you really need to have it pad on the right side instead, you could
write a small function to do it for you.  Here's one that's really simple:

def getRightPaddedString(mystring, width, padding_char=' '):
  return mystring + padding_char * (width - len(mystring))

Here's a demonstration of it:

>>> getRightPaddedString('item7', 10)
'item7     '
>>> getRightPaddedString('item17', 10)
'item17    '

Once you have something like getPaddedString, you can map the function
across all elements of your list:

  paddeditems = map(getPaddedString, items)

and do a simple loop through all your paddeditems, keeping track of how
many you've processed so far, and print a newline character whenever you
hit an index multiple of 3.

There are many ways of doing the output, so you might want to experiment
and see which is effective for you.