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!