Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables for width in Python format string

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?

like image 898
RolfBly Avatar asked Sep 14 '25 15:09

RolfBly


1 Answers

Using the f-string format becomes very easy nowadays.

If you were using

print(f'{token:10}')

And you want the 10 to be another variable (for example the max length of all the tokens), you would write

print(f'{token:{maxTokenLength}}')

In other words, enclose the variable within {}


In your particular case, all you need is this.

head = 'eggs', 'bacon', 'spam'  
w1, w2, w3 = 8, 7, 10  # column widths  

print(f'  {head[0]:>{w1}}  {head[1]:>{w2}}  {head[2]:>{w3}}')
print(f'  {"="*w1:>{w1}}  {"="*w2:>{w2}}  {"="*w3:>{w3}}')

Which produces

      eggs    bacon        spam
  ========  =======  ==========
like image 124
Rub Avatar answered Sep 16 '25 05:09

Rub