Skip to content

Instantly share code, notes, and snippets.

@Nachtalb
Forked from critiqjo/col_print.py
Last active February 9, 2018 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nachtalb/8a85c0793b4bea0a102b7414be5888d4 to your computer and use it in GitHub Desktop.
Save Nachtalb/8a85c0793b4bea0a102b7414be5888d4 to your computer and use it in GitHub Desktop.
Python: Multi-column printing of a list of strings
def col_print(lines, term_width=None, indent=0, pad=2):
"""Print list of strings in multiple columns
Original: https://gist.github.com/critiqjo/2ca84db26daaeb1715e1
Adjusted: https://gist.github.com/Nachtalb/8a85c0793b4bea0a102b7414be5888d4
"""
if not term_width:
size = shutil.get_terminal_size((80, 20))
term_width = size.columns
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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment