Created
August 12, 2021 02:28
-
-
Save ktbarrett/053513aed8ddd8ced3fd3c6eb964a80a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def build_table( | |
field_spec: List[Tuple[str, str, Optional[int]]], | |
table: List[Dict[str, str]], | |
) -> str: | |
field_fmts = [] | |
sep_line_fields = [] | |
field_names = [] | |
for name, alignment, width in field_spec: | |
if width is None: | |
width = max(len(name), *(len(row[name]) for row in table)) | |
field_fmts.append(f"{{{name}:{alignment}{width}}}") | |
sep_line_fields.append("-" * width) | |
field_names.append(format(name, f"{alignment}{width}")) | |
line_fmt = "".join(("| ", " | ".join(field_fmts), " |")) | |
sep_line = "".join(("+-", "-+-".join(sep_line_fields), "-+")) | |
header = "".join(("| ", " | ".join(field_names), " |")) | |
lines = [line_fmt.format(**row) for row in table] | |
return "\n".join((sep_line, header, sep_line, *lines, sep_line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment