Skip to content

Instantly share code, notes, and snippets.

@critiqjo
Created June 16, 2015 07:50
Show Gist options
  • Save critiqjo/2ca84db26daaeb1715e1 to your computer and use it in GitHub Desktop.
Save critiqjo/2ca84db26daaeb1715e1 to your computer and use it in GitHub Desktop.
Python: Multi-column printing of a list of strings
def col_print(lines, term_width=80, indent=0, pad=2):
n_lines = len(lines)
if n_lines == 0:
return
col_width = max(len(line) for line in lines)
n_cols = int((term_width + pad - indent)/(col_width + pad))
n_cols = min(n_lines, max(1, n_cols))
col_len = int(n_lines/n_cols) + (0 if n_lines % n_cols == 0 else 1)
if (n_cols - 1) * col_len >= n_lines:
n_cols -= 1
cols = [lines[i*col_len : i*col_len + col_len] for i in range(n_cols)]
rows = list(zip(*cols))
rows_missed = zip(*[col[len(rows):] for col in cols[:-1]])
rows.extend(rows_missed)
for row in rows:
print(" "*indent + (" "*pad).join(line.ljust(col_width) for line in row))
@Nachtalb
Copy link

Nachtalb commented Feb 9, 2018

You could add console size detection so that it is a bit more dynamic.

def col_print(lines, term_width=None, indent=0, pad=2):
    if not term_width:
        size = shutil.get_terminal_size((80, 20))
        term_width = size.columns
    ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment