In: Computer Science
python3
Continue from the previous function, write a draw_table method which draws a table of data. For example, consider the following code fragment:
my_table = Table([['Alice', 24], ['Bob', 19]], width=10) my_table.draw_table()
produces:
|Alice 24 | |Bob 19 |
Note: the column width is the value set up by the constructor. Insert a space in between columns.
and my previous function is
class Table:
def __init__(self,x, h = None, width=5):
self.x= x
self.h = h
self.w= width
def __str__(self):
return "headers={}, width={},
data={}".format(self.h,self.w,self.x)
'''
Python version : 3.6
Python program to create and test a class Table
'''
class Table:
def __init__(self,x, h = None, width=5):
self.x= x
self.h = h
self.w= width
def __str__(self):
return "headers={}, width={}, data={}".format(self.h,self.w,self.x)
def draw_table(self):
# loop over the x
for item in self.x:
print('|',end ='') # print the starting |
# loop over the item
for i in range(len(item)):
# print the ith position in item
# ljust returns a space padded string with the original string left-justified to a given width colum
print((str(item[i])).ljust(self.w,' '),end='')
print('|') # print the ending |
# test the function
my_table = Table([['Alice', 24], ['Bob', 19]], width=10)
my_table.draw_table()
#end of program
Code Screenshot:
Output: