"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Display Columnized Data in Python Like the \'column -t\' Command?

How to Display Columnized Data in Python Like the \'column -t\' Command?

Published on 2024-11-12
Browse:361

How to Display Columnized Data in Python Like the \'column -t\' Command?

Displaying Columnized Data in Python

In the realm of command-line administration tools, it is often desirable to present data in well-aligned columns. While tab characters provide a straightforward solution, they fail when dealing with data of varying lengths. This article aims to address this challenge by presenting a Python solution inspired by the behavior of the Linux 'column -t' command.

Python offers a powerful solution for creating aesthetically pleasing columnized output using format strings. From Python 2.6 , the following approach can be employed:

table_data = [
    ['a', 'b', 'c'],
    ['aaaaaaaaaa', 'b', 'c'],
    ['a', 'bbbbbbbbbb', 'c']
]
for row in table_data:
    print("{: >20} {: >20} {: >20}".format(*row))

This code utilizes the format string syntax to specify a minimum width of 20 characters and right-align the text within each column, ensuring a tidy and consistent presentation:

              a                    b                    c
aaaaaaaaaa                    b                    c
              a           bbbbbbbbbb                    c

This solution effectively mimics the behavior of the 'column -t' command, providing an elegant and versatile method for displaying tabular data in Python-based command-line tools and applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3