[Tutor] Formatting output into columns

Scott Oertel freebsd at scottevil.com
Thu Aug 30 21:18:15 CEST 2007


Someone asked me this question the other day, and I couldn't think of
any easy way of printing the output besides what I came up with pasted
below.

So what you have is a file with words in it as such:

apple
john
bean
joke
ample
python
nice

and you want to sort and output the text into columns as such:

a              p               j             b              n
apple      python     john       bean       nice
ample                      joke

and this is what works, but I would also like to know how to wrap the
columns, plus any ideas on a better way to accomplish this.

#!/usr/bin/env python

data = {}
lrgColumn = 0

for line in open("test.txt","r").read().splitlines():
    char = line[0].lower()
    if not char in data:
        data[char] = [line]
    else:
        data[char].append(line)

for item in data:
    print item.ljust(10),
    if len(data[item]) > lrgColumn:
        lrgColumn = len(data[item])
print

for item in range(lrgColumn):
    for i in data.iteritems():
        try:
            print i[1][item].ljust(10),
        except IndexError:
            print "".ljust(10),
    print



More information about the Tutor mailing list