render_table aligned plain-text output
Python
"""Render rows as an aligned plain-text table for terminal output."""
from typing import Any, Iterable, Sequence
def render_table(
headers: Sequence[str],
rows: Iterable[Sequence[Any]],
*,
separator: str = " | ",
right_align: set[int] | None = None,
) -> str:
"""Return the table as text, padding every column to its widest cell."""
right = right_align or set()
body = [["" if cell is None else str(cell) for cell in row] for row in rows]
widths = [len(header) for header in headers]
for row in body:
for index, cell in enumerate(row):
if index >= len(widths):
widths.append(len(cell))
else:
widths[index] = max(widths[index], len(cell))
def format_row(cells: Sequence[str]) -> str:
padded = [
cell.rjust(widths[index]) if index in right else cell.ljust(widths[index])
for index, cell in enumerate(cells)
]
return separator.join(padded).rstrip()
rule = separator.replace("|", "+").join("-" * width for width in widths)
lines = [format_row([str(header) for header in headers]), rule]
lines.extend(format_row(row) for row in body)
return "\n".join(lines)
if __name__ == "__main__":
rows = [(1, "Ada"), (2, "Bo Longname")]
print(render_table(["id", "name"], rows, right_align={0}))