Issue
How do I print a table that has 15 spaces reserved for every field and data inside those fields also has to be centered?
Something like this:
Name Address
-------------------- ---------------
Abcd Abcd
12345678901234567890 Abcd
Solution
You can use format
ting, join
and list comprehension:
headers = ['Name', 'Address']
value_lines = [
['Abcd', 'Abcd'],
['12345678901234567890', 'Abcd']
]
print(' '.join(['{:^25s}'.format(h) for h in headers]))
print(' '.join('-' * 25 for i in range(len(headers))))
for value_line in value_lines:
print(' '.join(['{:^25s}'.format(value) for value in value_line]))
Output:
Name Address
------------------------- -------------------------
Abcd Abcd
12345678901234567890 Abcd
If you need to increase column widths according to all values, it can be done this way:
headers = ['Name', 'Address']
value_lines = [
['Abcd', 'Abcd'],
['12345678901234567890', 'Abcd']
]
column_widths = [15] * len(headers)
for i, header in enumerate(headers):
column_widths[i] = max(column_widths[i], len(header))
for value_line in value_lines:
for i, value in enumerate(value_line):
column_widths[i] = max(column_widths[i], len(value))
print(' '.join([
('{:^' + str(column_widths[i]) + 's}').format(h)
for i, h in enumerate(headers)
]))
print(' '.join('-' * column_widths[i] for i in range(len(headers))))
for value_line in value_lines:
print(' '.join([
('{:^' + str(column_widths[i]) + 's}').format(value)
for i, value in enumerate(value_line)
]))
Output:
Name Address
-------------------- ---------------
Abcd Abcd
12345678901234567890 Abcd
Answered By - Yevgeniy Kosmak Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.