In order to print a header for tabular data, I'd like to use only one format string line and one spec for column widths w1, w2, w3 (or even w = x, y, z if possible.)
I've looked at this but tabulate etc. don't let me justify things in the column like format does.
This approach works:
head = 'eggs', 'bacon', 'spam'
w1, w2, w3 = 8, 7, 10 # column widths
line = ' {:{ul}>{w1}} {:{ul}>{w2}} {:{ul}>{w3}}'
under = 3 * '='
print line.format(*head, ul='', w1=w1, w2=w2, w3=w3)
print line.format(*under, ul='=', w1=w1, w2=w2, w3=w3)
Must I have individual names as widths {w1}, {w2}, ... in the format string? Attempts like {w[1]}, {w[2]}, give either KeyError or keyword can't be an expression.
Also I think the w1=w1, w2=w2, w3=w3 is not very succinct. Is there a better way?
w = {'w1': 8, 'w2': 7, 'w3': 10}then callline.format(..., **w). You could even build the dictionary dynamically from[8, 7, 10]-w = {'w{}'.format(index): value for index, value in enumerate([8, 7, 10], 1)}.