Formatting Tabular Data in Python: Aligning and Padding Columns
When working with tabular data in command-line tools, it's often necessary to present the data in a clean and readable format. In Python, formatting columns can be challenging due to varying data lengths.
One way to address this is to use plain tabs, but this approach assumes that the longest data in each row is known. For more flexible formatting, there are a few approaches to consider:
Using Python's Format Strings:
Since Python 2.6, format strings allow you to set a minimum width for columns and align text to the right. Here's an example:
<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>
This code will produce output where each column has a minimum width of 20 characters and the text is aligned to the right.
Output:
a b c aaaaaaaaaa b c a bbbbbbbbbb c
The above is the detailed content of How to Align and Pad Columns in Python for Readable Tabular Data?. For more information, please follow other related articles on the PHP Chinese website!