Skip to content

Instantly share code, notes, and snippets.

@laundmo
Last active May 27, 2024 21:42
Show Gist options
  • Save laundmo/2e2f7314570d2f86a4af8df4b1812b63 to your computer and use it in GitHub Desktop.
Save laundmo/2e2f7314570d2f86a4af8df4b1812b63 to your computer and use it in GitHub Desktop.
simple pretty print for tables
# This code is available under the MIT license: https://opensource.org/licenses/MIT
#
# 2022-07-29 Added from_dict helper, textwrapping, max_width, and typehinted to Sequence instead of list.
from itertools import zip_longest
import textwrap
from typing import Callable, List, Optional, Sequence
def text_width(text: str) -> int:
return len(max(text.split("\n"), key=len))
def max_text_width(texts: List[str]) -> int:
return len(max(texts, key=text_width))
def format_table(
table: Sequence[Sequence[str]],
headers: Optional[Sequence[str]] = None,
justify: Callable[[str, int], str] = str.ljust,
max_width: int = 20,
) -> str:
if headers is None:
headers = [""] * len(table)
col_lens = [
min(max_width, max_text_width([headers[i]] + list(col)))
for i, col in enumerate(table)
]
output = ""
if max(headers, key=len) != "":
output += (
" | ".join(justify(item, col_lens[i]) for i, item in enumerate(headers))
+ "\n"
)
output += " | ".join("-" * col_lens[i] for i, _ in enumerate(table)) + "\n"
for row in zip(*table):
justified = [justify(item, col_lens[i]) for i, item in enumerate(row)]
wrapped = [textwrap.wrap(i, width=max_width) for i in justified]
for line_elems in zip_longest(*wrapped, fillvalue=""):
output += (
" | ".join(
justify(item, col_lens[i]) for i, item in enumerate(line_elems)
)
+ "\n"
)
return output
def format_table_from_dict(
table: dict[str, List[str]],
justify: Callable[[str, int], str] = str.ljust,
max_width: int = 20,
):
return format_table(
list(table.values()),
headers=list(table.keys()),
justify=justify,
max_width=max_width,
)
print(format_table([["aaa, aaaaaa"], ["bb", "b"]], headers=["a", "a bunch of b's"]))
# a | a bunch of b's
# ----------- | --------------
# aaa, aaaaaa | bb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment