bck
bck

Reputation: 51

Print Python output into two columns

Trying to replicate a basic column command in a Python program to print a list of States to the user via the command line:

us_states_list_with_population = [   
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population: 
    print(state_name + " (" + state_abbreviation + ")")

Is there an easy way to split the output into two or three columns to make this shorter and more readable?

Desired output would be something like:

Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...

Versus:

Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...

Upvotes: 0

Views: 1206

Answers (2)

Errol
Errol

Reputation: 610

To achieve your desired OUTPUT you can try this.

us_states_list_with_population = [   
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
]

row = []
num_of_columns = 2
for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    row.append(f'{state_name} ({state_abbreviation})')
    if len(row) == num_of_columns:
        print(("\t").join(row))
        row.clear()
print(("\t").join(row)) # print last row if there is a remainder

Or if you want to learn more prettier tabulates check @cricket_007 comments.

Upvotes: 1

Robert Hafner
Robert Hafner

Reputation: 3885

You could separate them by tabs, rather than spaces.

for state_name , state_abbreviation , num_counties in us_states_list_with_population: 
    print(state_name + "\t(" + state_abbreviation + ")")

The \t there will get translated into a tab when printed.

Upvotes: 0

Related Questions