1

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
avocardio
  • 9
  • 1
  • 6

1 Answers1

0

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
Anon Coward
  • 9,784
  • 3
  • 26
  • 37