2

I have a program that prints some stuff in columns:

print("{: <7}{: <15}{: <75}{: <25}".format(sno, variable[1], variable[2], variable[3]))

Sometimes the values are too large or somewhat small, so I want to dynamically assign the spaces to the specific columns. So I loop through the stuff and get the maximum length of the string. Then I want to assign it to the number of spaces like this:

max = 10 #or any other integer which gets calculated dynamically.
print("{: <7}{: <15}{: <max}{: <25}".format(sno, variable[1], variable[2], variable[3]))

But this line gives me a ValueError: Invalid format specifier Error. Is there a better way to do this or do I have to hard-code the integer there?

Dhruv_2676
  • 101
  • 1
  • 9
  • It’s not a good idea to use `max` as a variable name as it’s overwriting the built in function. – S3DEV Apr 24 '21 at 10:17
  • Ok, That isn't a problem because I used that variable just to show an example here, I have other variable names! – Dhruv_2676 Apr 25 '21 at 09:56

2 Answers2

1

Your problem is that you want to treat max as a variable, but it is nothing more than a string, which is why python tries to recognize it as a format-specifier and fails.

You'd have to do it like this:

max = 10 #or any other integer which gets calculated dynamically.
format_str = '{: <7}{: <15}{: <' + str(max) + '}{: <25}'
print(format_str.format(sno, variable[1], variable[2], variable[3]))

Notice that I'm constructing the format-string with the value of max, not just the string "max".

1

You may use python's (version >= 3.6.x) f-String formatting:

max = 10
print(f"{sno: <7}{variable[1]: <15}{variable[2]: <{max}}{variable[3]: <25}")

PEP 498 -- Literal String Interpolation

AcK
  • 2,063
  • 2
  • 20
  • 27