Home > Article > Backend Development > How to Create Columnized Output in Python Using Format Strings?
Creating Columnized Output in Python
Problem:
In Python, you want to create a column-aligned list of data, similar to the output of the Linux 'column -t' command, which dynamically adjusts column widths based on the longest value present.
Solution:
Using Python 2.6 Format Strings:
Python's format strings provide a powerful mechanism for formatting and aligning data. To create a columnized list 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>
The {: >20} format specifier indicates that each value should be right-aligned in a column of at least 20 characters wide. This ensures that the columns are aligned regardless of the length of individual values.
Output:
a b c aaaaaaaaaa b c a bbbbbbbbbb c
The above is the detailed content of How to Create Columnized Output in Python Using Format Strings?. For more information, please follow other related articles on the PHP Chinese website!