Issue
I am trying to create a nice column list in python for use with commandline admin tools which I create.
Basicly, I want a list like:
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
To turn into:
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
Using plain tabs wont do the trick here because I don't know the longest data in each row.
This is the same behavior as 'column -t' in Linux..
$ echo -e "a b c\naaaaaaaaaa b c\na bbbbbbbbbb c"
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
$ echo -e "a b c\naaaaaaaaaa b c\na bbbbbbbbbb c" | column -t
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
I have looked around for various python libraries to do this but can't find anything useful.
Solution
data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
What this does is calculate the longest data entry to determine the column width, then use .ljust()
to add the necessary padding when printing out each column.
Answered By - Shawn Chin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.