How to set Python .format() padding at runtime?


I’m new to python and trying to print formatted columns of array items to the screen. I found the .format() method which can use fixed-width padding to separate the columns.

$ ./ 
Num  EmpID Name     Team
1    23    Alex     Sales
2    10    Alan     Admin

This works OK until one of the items is longer than expected, or Num ends up longer than a single digit, or…:

Num  EmpID Name     Team
1    23    Alexandria Sales
2    10    Alan     Quality Assurance

What I’d like to do is loop over all the items in user_list and find the longest element (Quality Assurance in the code below) and tell .format() to pad all items based on that length. I haven’t stumbled across a way to do this however.

Is there a way to define the .format() padding at runtime somehow?


class user (object):
  __slots__ =  "name", "team", "empid"

  def __init__ (self):        = None        = None
    self.empid       = None

def print_menu (user_list):
   index = 0
   print ("{:<4} {:<5} {:<8} {}".format ("Num", "EmpID", "Name", "Team"))
   for person in user_list:
      index = index + 1
      print ("{:<4} {:<5} {:<8} {}".format (str(index), str(person.empid),,

new_user = user() = "Alexandria" = "Sales"
new_user.empid = "23"

new_user = user() = "Alan" = "Quality Assurance"
new_user.empid = "10"

print_menu (users)

>Solution :

Absolutly, the trick is to know that you can nest the brackets {} in a format string. You would do this in place of the numbers 4,5,or 8 in a string like "{:<4} {:<5} {:<8} {}"

heres a quick example:

longestName = 8
someObj = (5,2)

That print results in : "_(5, 2) _"
As you can see it has been padded to some integer we can get beforehand by just iterating over all the items and storing the longest item before printing.

Leave a Reply Cancel reply