Home  >  Article  >  Backend Development  >  How to Create a Formatted Column Output in Python?

How to Create a Formatted Column Output in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 00:51:30941browse

How to Create a Formatted Column Output in Python?

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:

  • Right-aligns text for consistent spacing.
  • Adjusts the minimum column width using the number provided in the format string (e.g., {: >20}).
  • Accommodates data of varying lengths in each row, providing a readable table format.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn