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

How to Create a Formatted Column Output in Python?

Barbara Streisand
Release: 2024-11-03 00:51:30
Original
1013 people have browsed it

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>
Copy after login

Output:

               a                    b                    c
      aaaaaaaaaa                    b                    c
               a           bbbbbbbbbb                    c
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template