Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I line up text from python into columns in my terminal?

Tags:

python

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?

like image 704
Hobhouse Avatar asked Aug 31 '09 06:08

Hobhouse


People also ask

How do you align text in a text file in Python?

To set the alignment, use the character < for left-align, ^ for center, > for right. To set padding, precede the alignment character with the padding character ( - and .

How do you align print statements in Python?

Aligning the output neatly using f-prefix You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.


1 Answers

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.

like image 121
Vinay Sajip Avatar answered Sep 18 '22 06:09

Vinay Sajip