4
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.

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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))

2 Comments

Exactly what I wanted!
note that I answered exactly this a few minutes before.
1

Try:

(str(longest).join(['{:^','}|{:^','}|{:^','}']).format(col1,col2,col3))

1 Comment

I like the answer, it's very creative, but not what I was looking for.
1
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 }'

3 Comments

Your answer was not chosen because 3 curly brackets were not needed to accomplish this.
Of course not! I didn't read the documentation but just went with this. The approach in the accepted answer is the best one and is also documented.
@Jean-FrançoisFabre: It looks like your answer is accepted now. Might be that OP didn't see it earlier with too many answer flowing in. And, my comment about the accepted answer is still valid then ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.