Create Formatted Column Output in Python
Question:
In terminal administration tools, how can a user-friendly column list be created in Python?
Objective:
To transform a list of variable-length data into a tabular format with evenly spaced columns, like the one shown below:
a | b | c |
---|---|---|
aaaaaaaaaa | b | c |
a | bbbbbbbbbbb | c |
Solution:
Python 2.6 offers a simple method using format strings:
<code class="python">table_data = [ ['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'] ] for row in table_data: print("{: >20} {: >20} {: >20}".format(*row))</code>
Output:
a b c aaaaaaaaaa b c a bbbbbbbbbb c
Benefits:
The above is the detailed content of How to Create a Formatted Column Output in Python?. For more information, please follow other related articles on the PHP Chinese website!