Reputation: 481
longest = len(max(l))
for col1, col2, col3 in zip(l[::3],l[1::3],l[2::3]):
print('{:^20}|{:^20}|{:^20}'.format(col1,col2,col3))
how can I use longest
in place of the 20
so that my formatting will always fit? I also don't want my code looking ugly, so if possible, use formatting or some other way.
Upvotes: 4
Views: 2548
Reputation: 140168
You can pass the width directly in the format:
for cols in zip(l[::3],l[1::3],l[2::3]):
print('{:^{width}}|{:^{width}}|{:^{width}}'.format(*cols,width=longest))
(adapted from an example quoted in the documentation)
and you don't have to unpack the columns manually. Just unpack them with *
in the format
call.
Upvotes: 5
Reputation: 42758
Formats can be nested:
longest = len(max(l))
for col1, col2, col3 in zip(l[::3],l[1::3],l[2::3]):
print('{:^{len}}|{:^{len}}|{:^{len}}'.format(col1,col2,col3, len=longest))
Upvotes: 3
Reputation: 19811
longest = len(max(l))
# tpl will be '{:^20}|{:^20}|{:^20}'
tpl = '{{:^{longest}}}|{{:^{longest}}}|{{:^{longest}}}'.format(longest=longest)
for col1, col2, col3 in zip(l[::3],l[1::3],l[2::3]):
print(tpl.format(col1,col2,col3))
You can first create the template and then insert the columns.
Double curly braces can be used if you want to literally have the braces in the output:
>>> "{{ {num} }}".format(num=10)
'{ 10 }'
Upvotes: 1
Reputation: 7055
Try:
(str(longest).join(['{:^','}|{:^','}|{:^','}']).format(col1,col2,col3))
Upvotes: 1