[Tutor] Alternative File I/O for Tuples

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Jun 26 07:48:34 CEST 2005



> I would like to see something more like when the file is printed:
>
> Austin    James    704-111-1234
> Austin    Janet    704-111-1234
> etc.
>
> Is this a simple task, or am I jumping into deep water? :)


Hi Don,

Not too bad; I think you'll looking for "String Formatting":

    http://www.python.org/doc/lib/typesseq-strings.html

The idea is that we use a template to lay out the rows.  This template
gives the general shape of what we want.

In your example, it looks like every row is ten characters long.  A
template that can lay out two values as two columns might looks something
like this:

######
>>> "%10s%10s" % ("Curious", "George")
'   Curious    George'
######


Oh, it's justified right.  Let me switch that over:

######
>>> "%-10s%-10s" % ("Curious", "George")
'Curious   George    '
######

Ok, that's better.  *grin*  So you should be able to generalize this to
build up these nicely formatted lines that can be printed at once.


There are some other sophisticated string-formatting tools in Python, many
of which live in strings themselves.

    http://www.python.org/doc/lib/string-methods.html

For example, strings even know how to "center" themselves:

######
>>> 'I am a centered sentence.'.center(40)
'       I am a centered sentence.        '
######



If you have more questions, please feel free to ask.



More information about the Tutor mailing list