-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_str.py
71 lines (57 loc) · 1.73 KB
/
table_str.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
67
68
69
70
71
#!/usr/bin/env python3
def format_row(values, max_width, top_line):
"""
Returns a formated row as a string.
Parameters:
values: a list ove values for each column
max_width: (int) max column width
top_line: (boolean) print a top-line
"""
output = ''
if max_width % 2 == 0:
max_width += 1
# formate center of row
for value in values:
output += ' | ' + str(value).center(max_width, ' ')
output = '|' + output[1:] + ' ||'
# add top and or bottom lines
row_width = len(output)
line = '-' * row_width
if top_line:
line = '=' * row_width
output = line + '\n' + output + '\n' + line
else:
output += '\n' + '-' * row_width
return output
def print_result_table(message, col_names, list_of_tup):
"""
Takes a list of table rows as tuples, and prints out a table.
Parameters:
message: print a message before the table
col_names: names of each column in the table.
list_of_tup: a list of tuples
"""
print(message)
output_list = []
col_width = 0
padding = 3
# find logest col
for item in list_of_tup:
for item_a in item:
width = len(str(item_a))
if width > col_width:
col_width = width
for item in col_names:
width = len(item)
if width > col_width:
col_width = width
# Add column labels
output_list.append(format_row(col_names, col_width + padding, True))
for item in list_of_tup:
row_items = []
for item_a in item:
row_items.append(item_a)
output_list.append(format_row(row_items, col_width + padding, False))
for item in output_list:
print(item)
print('\n')