Home > Backend Development > Python Tutorial > How to Create Columnized Output in Python Using Format Strings?

How to Create Columnized Output in Python Using Format Strings?

Patricia Arquette
Release: 2024-11-02 21:05:30
Original
214 people have browsed it

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

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

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!

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