-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathascii_table__simple_pretty__rjust.py
66 lines (47 loc) · 1.64 KB
/
ascii_table__simple_pretty__rjust.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def pretty_table(data, cell_sep=" | ", header_separator=True) -> str:
rows = len(data)
cols = len(data[0])
col_width = []
for col in range(cols):
columns = [str(data[row][col]) for row in range(rows)]
col_width.append(len(max(columns, key=len)))
separator = "-+-".join("-" * n for n in col_width)
lines = []
for i, row in enumerate(range(rows)):
result = []
for col in range(cols):
item = str(data[row][col]).rjust(col_width[col])
result.append(item)
lines.append(cell_sep.join(result))
if i == 0 and header_separator:
lines.append(separator)
return "\n".join(lines)
def print_pretty_table(data, cell_sep=" | ", header_separator=True):
print(pretty_table(data, cell_sep, header_separator))
if __name__ == "__main__":
table_data = [
["FRUIT", "PERSON", "ANIMAL"],
["apples", "Alice", "dogs"],
["oranges", "Bob", "cats"],
["cherries", "Carol", "moose"],
["banana", "David", "goose"],
]
print_pretty_table(table_data, header_separator=False)
# FRUIT | PERSON | ANIMAL
# apples | Alice | dogs
# oranges | Bob | cats
# cherries | Carol | moose
# banana | David | goose
print()
print_pretty_table(table_data)
# FRUIT | PERSON | ANIMAL
# ---------+--------+-------
# apples | Alice | dogs
# oranges | Bob | cats
# cherries | Carol | moose
# banana | David | goose
print()
print_pretty_table([["FRUIT", "PERSON", "ANIMAL"]])