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?
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With