0

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)
...
bck
  • 51
  • 4
  • What is so *not* easy about the method you posted? It's straightforward and easy to read. The next step would be to convert your list to a Pandas data frame and dump formatted output from there, but this method has more overhead. – Prune Feb 15 '20 at 00:13
  • Are you looking for merely output formatting? If so, that's an easy browser search for the documentation. – Prune Feb 15 '20 at 00:14
  • Yes, this would be in accordance with output formatting to generate two separate columns. – bck Feb 15 '20 at 00:17
  • Pandas handles tabular data much better – OneCricketeer Feb 15 '20 at 00:22
  • Does this answer your question? [Create nice column output in python](https://stackoverflow.com/questions/9989334/create-nice-column-output-in-python) – Aryeh Katz Feb 15 '20 at 18:27

2 Answers2

1

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.

Errol
  • 600
  • 4
  • 16
0

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.

Robert Hafner
  • 3,364
  • 18
  • 23