My code and funcs for printing to columns in 2.7 and 3.0+ using print(). I had to relearn column formatting as I moved to using the print() function, and so the follwing is a result. Inspired and partially copied from discussion on StackOverflow

def main():
        # Main Code
    v_Data = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'bbbbbbbbbbbbbbbbbbb', 'c'], ['k', 'k', 'l'], ['a', 'b', 'c']] ## Each bracketed item is a 'row', non-bracketed ithems are broken into seprate rows
    f_PrintToFixedColumns(v_Data)
    print()

    print("Var Cols")
    f_PrintToVarColumns(v_Data)


def f_PrintToFixedColumns(v_Data):
    """Syntax: (list); Returns: (print);
    Desc.: Takes a list and finds longest data item, then prints in columns
    formated to width of that max width.
    Test: f_PrintToColumns(v_Data) [See main for test data.]"""
    v_ColWidth = max(len(word) for row in v_Data for word in row) + 2  # paddingGet max length 'word' from 'word' per 'row'
    for j, row in enumerate(v_Data):
        print("".join(word.ljust(v_ColWidth) for word in row))

def f_PrintToVarColumns(v_Data):
    """Syntax: (list); Returns: (print);
    Desc.: Takes a list and prints each column to width of longest member.
    Test: f_PrintToVarColumns(v_Data) [See main for test data.]"""
    widths = [max(map(len, col)) for col in zip(*v_Data)]
    for row in v_Data:
        print("  ".join((val.ljust(width) for val, width in zip(row, widths))))

@Gribouillis: That's cool. I may use that in the future, as one can just pop. a list and then dynamically print it out in multicolumns. Useful. Thanks.

Edited 1 Year Ago by BustACode: Add Respondee

I have used module prettytable in the past this way ...

''' prettytable102.py
explore module prettytable

get
prettytable-0.7.2.zip
from
https://pypi.python.org/pypi/PrettyTable
extract the zip file and copy prettytable.py to /Lib/side-packages
'''

from prettytable import PrettyTable

mylist = [['a', 'b', 'c'], ['a', 'b', 'c'],
['a', 'bbbbbbbbbbbbbbbbbbb', 'c'],
['k', 'k', 'l'], ['a', 'b', 'c']]

header = ["Column1", "Column2", "Column3"]
pt = PrettyTable(header)
# left align the following columns (center is default)
pt.align["Column1"] = "l"
pt.align["Column2"] = "l"
pt.align["Column3"] = "l"
# space between column edges and contents (1 = default)
pt.padding_width = 2

for sublist in mylist:
    pt.add_row(sublist)

print(pt)

''' result ...
+-----------+-----------------------+-----------+
|  Column1  |  Column2              |  Column3  |
+-----------+-----------------------+-----------+
|  a        |  b                    |  c        |
|  a        |  b                    |  c        |
|  a        |  bbbbbbbbbbbbbbbbbbb  |  c        |
|  k        |  k                    |  l        |
|  a        |  b                    |  c        |
+-----------+-----------------------+-----------+
'''

Gribouillis' module is smoother.

Edited 1 Year Ago by vegaseat

This question has already been answered. Start a new discussion instead.