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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With