PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to print this information in a good format (vertical alignment) in python?

 November 16, 2022     alignment, iteration, python, vertical-alignment     No comments   

Issue

Im trying to have this information align vertically and not overlap. I have only used print("\t xyz \t") for each iteration and it prints it side by side, as it should, but some strings are longer than others.

How it is

How I want it

Current Output:

Ticker :         GME          

Employees :        14000         

Title :     CEO & Director      Exec. VP & CFO      Exec. VP & Chief Merchandising Officer

Name :      Mr. George E. Sherman       Mr. James Anthony Bell  Mr. Chris R. Homeister

Ages :      58      52      51

Pay :       1,900,374 USD       801,318 USD     766,266 USD

Solution

Generally the way to do this is to either hard code the size of each column, or run through the data, and find a column width to use for each column.

If you want to loop through and adapt the column width, the code is fairly straight forward:

rows = [
    ["Ticker :", "GME"],
    ["Employees :", "14000"],
    ["Title :", "CEO & Director", "Exec. VP & CFO", "Exec. VP & Chief Merchandising Officer"],
    ["Name :", "Mr. George E. Sherman", "Mr. James Anthony Bell", "Mr. Chris R. Homeister"],
    ["Ages :", "58", "52", "51"],
    ["Pay :", "1,900,374 USD", "801,318 USD", "766,266 USD"],
]

# Build up a max length of each column
lengths = {}
for row in rows:
    for i in range(len(row)):
        lengths[i] = max(lengths.get(i, 0), len(row[i]))

for row in rows:
    # For each cell, padd it by the max length
    output = ""
    for i in range(len(row)):
        if len(output) > 0:
            # Add a space between columns
            output += " "
        cell = row[i] + " " * lengths[i]
        cell = cell[:lengths[i]]
        output += cell
    print(output)

This will output:

Ticker :    GME
Employees : 14000
Title :     CEO & Director        Exec. VP & CFO         Exec. VP & Chief Merchandising Officer
Name :      Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages :      58                    52                     51
Pay :       1,900,374 USD         801,318 USD            766,266 USD


Answered By - Anon Coward
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing