Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting string based on maximum length

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.

like image 809
lol Avatar asked Dec 24 '22 21:12

lol


2 Answers

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.

like image 90
Jean-François Fabre Avatar answered Jan 01 '23 18:01

Jean-François Fabre


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))
like image 44
Daniel Avatar answered Jan 01 '23 20:01

Daniel