-
-
Save acatton/9303e3a53fae80b6b0cd607fd51b95a0 to your computer and use it in GitHub Desktop.
Render data
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 render_table(data: List[List[str]]) -> str: | |
"""Render table: | |
Example: | |
>>> print(render_table([['a', 'b'], ['c', 'd'], ['long', 'very long']])) | |
+------+-----------+ | |
| a | b | | |
+------+-----------+ | |
| c | d | | |
+------+-----------+ | |
| long | very long | | |
+------+-----------+ | |
""" | |
if not len({len(l) for l in data}) > 0: | |
raise ValueError("All row should have the same length") | |
# 2 is for spaces on each sides | |
lengths = [max(len(s) for s in col) + 2 for col in transpose(data)] | |
separation = wrap(('-' * col_len for col_len in lengths), '+') | |
rows = ( | |
wrap(('{: ^{length}}'.format(val, length=l) for val, l in zip(row, lengths)), '|') | |
for row in data | |
) | |
acc = [separation] | |
for r in rows: | |
acc.append(r) | |
acc.append(separation) | |
return '\n'.join(acc) | |
def render_datamap(data: List[Tuple[str, str]]) -> str: | |
"""Render multiline mapped data elements: | |
Example: | |
>>> print(render_datamap([ | |
... ('Key', 'value'), | |
... ('Other key', 'multi\\nlines'), | |
... ('Last', 'but not least') | |
... ])) | |
Key: value | |
Other key: multi | |
lines | |
Last: but not least | |
""" | |
acc = [] | |
keylen = max(len(k) for k, _ in data) | |
for key, value in data: | |
# There's always at least one element in split | |
first, *other = value.split('\n') | |
acc.append('{: >{length}}: {}'.format(key, first, length=keylen)) | |
acc.extend('{: >{length}} {}'.format('', l, length=keylen) for l in other) | |
return '\n'.join(acc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment