[Tutor] tabbed output

Hugo Arts hugo.yoshi at gmail.com
Mon Feb 13 02:11:51 CET 2012


On Mon, Feb 13, 2012 at 1:52 AM, Michael Lewis <mjolewis at gmail.com> wrote:
> I am having a weird issue. I have a print statement that will give me
> multiple outputs separated by a tab; however, sometimes there is a tab
> between the output and sometimes there is not. It seems sort of sporadic. My
> code is below and two sample outputs are below that (one that works how I
> expect, and the other showing the issue (tab separation not occurring
> between all pieces of the output) What is going on?
>
> def CheckNames():
>     names = []
>     for loop in range(1,4):
>         while True:
>             name = raw_input('''Name #%s: ''' %(loop))
>             if name not in names:
>                 names.append(name)
>                 break
>             print '%s is already in the data. Try again.' %(name)
>     sorted_names = sorted(names)
>     for element in list(sorted_names):
>         print 'Hurray for %s!\t' %(element),
>
> Sample Output1:
>
> Name #1: mike
> Name #2: bret
> Name #3: adam
> Hurray for adam!            Hurray for bret!   Hurray for mike!
>
> Sample Output2(there is a tab between output 2 & 3, but not 1 & 2):
>

Yes there is, and I'll show you by modifying your method just a little:

>>> def CheckNames():
    names = []
    for loop in range(1,4):
        while True:
            name = raw_input('''Name #%s: ''' %(loop))
            if name not in names:
                names.append(name)
                break
            print '%s is already in the data. Try again.' %(name)
    sorted_names = sorted(names)
    lst = []
    for element in list(sorted_names):
        lst.append('Hurray for %s!\t' %(element))
    return ''.join(lst)

The juicy bit is at the end. Instead of printing, we make a list,
append everything we were going to print to it, join it into one big
string, and return it. This way we can look at the string better. Now
for the demonstration:

>>> CheckNames()
Name #1: abe
Name #2: alan
Name #3: adam
'Hurray for abe!\tHurray for adam!\tHurray for alan!\t'
>>> print _   # btw, _ is short for last value in the interpreter
Hurray for abe!	Hurray for adam!		Hurray for alan!	
>>>

You see that? in the string returned, there is most definitely a tab.
And in fact, that little space between abe and adam, that is also a
tab. You see, if you insert a tab, the cursor is moved up to the next
tab stop. Choosing a short name #1, like abe, means that the next tab
stop is right after the exclamation mark. If you use a slightly longer
name though, like adam, the exclamation mark will be past that tab
stop, and the tab character afterward will put name #2 all the way at
the next tabstop.

tab characters are lame like that. They are generally only used to
make sure output lines up at a tabstop, it's not a reliable way to put
a certain amount of space between two pieces of text.

HTH,
Hugo


More information about the Tutor mailing list