tags:

views:

309

answers:

3

I'm printing out some values from a script in my terminal window like this:

for i in items:
    print "Name: %s Price: %d" % (i.name, i.price)

How do I make these line up into columns?

+7  A: 

If you know the maximum lengths of data in the two columns, then you can use format qualifiers. For example if the name is at most 20 chars long and the price will fit into 10 chars, you could do

print "Name: %-20s Price: %10d" % (i.name, i.price)

This is better than using tabs as tabs won't line up in some circumstances (e.g. if one name is quite a bit longer than another).

If some names won't fit into usable space, then you can use the . format qualifier to truncate the data. For example, using "%-20.20s" for the name format will truncate any longer names to fit in the 20-character column.

Vinay Sajip
Excellent. Another reminder for me of a function I rarely use in python. Was having this problem myself earlier and fixed it with tabs. Now I can go back and make my code easier to read.
Dan Goldsmith
+4  A: 

As Vinay said, use string format specifiers.

If you don't know the maximum lengths, you can find them by making an extra pass through the list:

maxn, maxp = 0, 0
for item in items:
    maxn = max(maxn, len(item.name))
    maxp = max(maxp, len(str(item.price)))

then use '*' instead of the number and provide the calculated width as an argument.

for item in items:
    print "Name: %-*s Price: %*d" % (maxn, item.name, maxp, item.price)
John Fouhy
A: 

You can also use the rjust() / ljust() methods for str objects.