2

I am attempting to use str.format() for report headers (i.e., columns) with variable widths, but I can't seem to do it using an int variable:

hlist =['h1','h2','h3','h4']
width = 7

for i in range(len(hlist)):
    # print(hlist[i].center(width), end='  ')       # this works
    print('{:^width}'.format(hlist[i]), end='  ')   # this doesn't
print()

for i in range(len(hlist)):
    # print('------'.center(width), end='  ')       # this works
    print('{:-<width}'.format('-'), end='  ')       # this doesn't
print()

Running this code gives me:

ValueError: Invalid format specifier

Using any int literal in place of width works fine. I researched here and I thought I was getting close with the format_spec arg, but it looks like it only supports non-integer formats. I tried int() as well, but no luck.

I'm happy with the solution that works using byte.center() but I was looking for a way to make use of the newer syntax for more flexibility.

Any help with this would be much appreciated!

0

1 Answer 1

0

You have to pass the width as a variable to the format function, and let it know that you want a variable named width, not a literal string. Since braces can be nested, do this:

hlist =['h1','h2','h3','h4']
width = 7

for i in range(len(hlist)):
    print('{:^{width}}'.format(hlist[i], width=width), end='  ')
print()

for i in range(len(hlist)):
    print('{:-<{width}}'.format('-', width=width), end='  ')
print()
Sign up to request clarification or add additional context in comments.

6 Comments

This is good, thank you. I'm brand new at this, but can you tell me what happened to the previous answer to this question? It seems to have been removed. I thought questions just got voted up, not removed...?
Not sure actually. I am guessing that the owner deleted it. I don't think it was too terrible, even if it wasn't the canonical answer, so I doubt that a moderator removed it.
Yes, perhaps the user did that; your answer was more to my point. I did vote up the answer, however I'm too new for my upvotes to show publicly :-\ Thanks again...
That's OK. Can you select the answer once the question is closed?
Yes, it seems I can. I receive this message after I vote an answer up : Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.