dblume commited on 2023-03-04 21:00:11
Showing 1 changed files, with 50 additions and 0 deletions.
Might refactor this later, just wanted to save this handy snippet.
... | ... |
@@ -0,0 +1,50 @@ |
1 |
+#!/usr/bin/env python3 |
|
2 |
+from typing import Sequence |
|
3 |
+ |
|
4 |
+__author__ = "David Blume" |
|
5 |
+__copyright__ = "Copyright 2016-2023, David Blume" |
|
6 |
+__license__ = "MIT" |
|
7 |
+__version__ = "1.0" |
|
8 |
+__status__ = "Development" |
|
9 |
+ |
|
10 |
+def print_table(rows: Sequence[Sequence[str]], |
|
11 |
+ underline_header: str='-', |
|
12 |
+ col_delimiter: str="\t", |
|
13 |
+ outside_delimiters: bool=False): |
|
14 |
+ """Prints rows with consistent column widths.""" |
|
15 |
+ cols = zip(*rows) |
|
16 |
+ |
|
17 |
+ # Compute column widths by taking maximum length of values per column |
|
18 |
+ col_widths = [max(len(value) for value in col) for col in cols] |
|
19 |
+ |
|
20 |
+ # Create a suitable format string for nice table output |
|
21 |
+ fmt = col_delimiter.join(["{:<%d}" % i for i in col_widths]) |
|
22 |
+ if outside_delimiters: |
|
23 |
+ fmt = f"{col_delimiter.lstrip()}{fmt}{col_delimiter.rstrip()}" |
|
24 |
+ |
|
25 |
+ # Print each row using the computed format |
|
26 |
+ if underline_header: |
|
27 |
+ print(fmt.format(*rows[0])) |
|
28 |
+ if outside_delimiters: |
|
29 |
+ print(col_delimiter.lstrip() + col_delimiter.join([(underline_header * i) for i in col_widths]) + col_delimiter.rstrip()) |
|
30 |
+ else: |
|
31 |
+ print(col_delimiter.join([(underline_header * i) for i in col_widths])) |
|
32 |
+ else: |
|
33 |
+ print(fmt.format(*rows[0])) |
|
34 |
+ for row in rows[1:]: |
|
35 |
+ print(fmt.format(*row)) |
|
36 |
+ |
|
37 |
+ |
|
38 |
+if __name__ == '__main__': |
|
39 |
+ t = (("Header 1", "Header 2", "Header 3"), |
|
40 |
+ ("Row one", "Row one, longer cell", "R1.3"), |
|
41 |
+ ("Row two, long cell", "Row two", "R2.3")) |
|
42 |
+ print_table(t, None) |
|
43 |
+ print() |
|
44 |
+ print_table(t) |
|
45 |
+ print() |
|
46 |
+ print_table(t, underline_header='=', col_delimiter=" ") |
|
47 |
+ print() |
|
48 |
+ print_table(t, None, col_delimiter=" | ", outside_delimiters=True) |
|
49 |
+ print() |
|
50 |
+ print_table(t, col_delimiter=" | ", outside_delimiters=True) |
|
0 | 51 |