Create a text table using Unicode characters. Args: rows: A list of tuples/lists to be displayed in the table. width: Maximum width of the table.
(rows: Sequence[Sequence[str]], width: int = 100)
| 9 | |
| 10 | |
| 11 | def make_table(rows: Sequence[Sequence[str]], width: int = 100) -> str: |
| 12 | """Create a text table using Unicode characters. |
| 13 | |
| 14 | Args: |
| 15 | rows: A list of tuples/lists to be displayed in the table. |
| 16 | width: Maximum width of the table. |
| 17 | """ |
| 18 | if not rows: |
| 19 | return '' |
| 20 | |
| 21 | num_cols = max(len(row) for row in rows) |
| 22 | |
| 23 | if num_cols == 0: |
| 24 | return '' |
| 25 | |
| 26 | # Normalize the row size by filling missing columns with empty values |
| 27 | normalized_rows = [list(row) + [''] * (num_cols - len(row)) for row in rows] |
| 28 | col_widths = [max(len(str(row[i])) for row in normalized_rows) for i in range(num_cols)] |
| 29 | total_width = sum(col_widths) + (3 * num_cols) + 1 |
| 30 | |
| 31 | # If the table size is larger than `width`, set all columns to the same length |
| 32 | col_widths = col_widths if total_width <= width else [max(3, (width - (3 * num_cols) - 1) // num_cols)] * num_cols |
| 33 | |
| 34 | # Initialize borders |
| 35 | top_parts, bottom_parts = [BORDER['TL']], [BORDER['BL']] |
| 36 | |
| 37 | for i in range(num_cols): |
| 38 | h_border = BORDER['H'] * (col_widths[i] + 2) |
| 39 | top_parts.append(h_border) |
| 40 | bottom_parts.append(h_border) |
| 41 | |
| 42 | if i < num_cols - 1: |
| 43 | top_parts.append(BORDER['TM']) |
| 44 | bottom_parts.append(BORDER['BM']) |
| 45 | else: |
| 46 | top_parts.append(BORDER['TR']) |
| 47 | bottom_parts.append(BORDER['BR']) |
| 48 | |
| 49 | top_border, bottom_border = ''.join(top_parts), ''.join(bottom_parts) |
| 50 | |
| 51 | result = [top_border] |
| 52 | |
| 53 | for row in normalized_rows: |
| 54 | cells = [] |
| 55 | |
| 56 | for i, cell in enumerate(row): |
| 57 | # Trim the content if the length exceeds the widths of the column |
| 58 | norm_cell = f'{cell[: col_widths[i] - 3]}...' if len(cell) > col_widths[i] else cell.ljust(col_widths[i]) |
| 59 | cells.append(norm_cell) |
| 60 | |
| 61 | # row: │ cell1 │ cell2 │ ... |
| 62 | row_str = BORDER['V'] + ''.join(f' {cell} {BORDER["V"]}' for cell in cells) |
| 63 | result.append(row_str) |
| 64 | |
| 65 | result.append(bottom_border) |
| 66 | |
| 67 | return '\n'.join(result) |
no outgoing calls