Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

$ ./format.py 
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…:

./format.py 
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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

    #!/usr/bin/python3

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

  def __init__ (self):
    self.name        = None
    self.team        = 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), person.name, person.team))


users=[]
new_user = user()

new_user.name = "Alexandria"
new_user.team = "Sales"
new_user.empid = "23"
users.append(new_user)

new_user = user()
new_user.name = "Alan"
new_user.team = "Quality Assurance"
new_user.empid = "10"
users.append(new_user)

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)
print(f'_{str(someObj):<{longestName}}_')

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading