First of all, I would like to apologise that I couldn't mention the topic name well for this question. I was trying to print a table of customer records with the column length and records length will automatically be align perfectly.
customer_list = [["ctm1","jacon","jackson@gmail.com","+60166197213","15/5/1990","jadsfsd23"],["ctm1","jacksonmartin","jacksonmartinez@gmail.com","+60166197213","15/5/1990","jadsfsddfdf23"]]
# show records of customer account info
def view_customer_account():
# initialize column length
Ctm_ID_CL, Usrname_CL, Email_CL = 2,8,13
# loop for longest data length and make it as column length
# column length will remain as initial column length if longest data length is shorter than it
for customer in customer_list:
if len(customer[0]) > Ctm_ID_CL:
Ctm_ID_CL = len(customer[0])
if len(customer[1]) > Usrname_CL:
Usrname_CL = len(customer[1])
if len(customer[2]) > Email_CL:
Email_CL = len(customer[2])
# print column name
# column name string will concatenate with a space which multiply with (column length - initial column length)
print(f'| ID{" "*(Ctm_ID_CL-2)} | Username{" "*(Usrname_CL-8)} | Email Address{" "*(Email_CL-13)} | Phone number | Date of birth |')
# print records
# records(str) will concatenate with a space which multiply with (column length/initial column length) - records str length
for customer in customer_list:
print(f'| {customer[0]+" "*(Ctm_ID_CL-len(customer[0]))} | {customer[1]+" "*(Usrname_CL-len(customer[1]))} | {customer[2]+" "*(Email_CL-len(customer[2]))} | {customer[3]} | {customer[4]}'+" "*5+"|")
view_customer_account()
However, the way I look for the longest string length for each item in the list and make it as the length of column will get duplicated a lot when there is more field coming in, which is this part:
# initialize column length
Ctm_ID_CL, Usrname_CL, Email_CL = 2,8,13
# loop for longest data length and make it as column length
# column length will remain as initial column length if longest data length is shorter than it
for customer in customer_list:
if len(customer[0]) > Ctm_ID_CL:
Ctm_ID_CL = len(customer[0])
if len(customer[1]) > Usrname_CL:
Usrname_CL = len(customer[1])
if len(customer[2]) > Email_CL:
Email_CL = len(customer[2])
# more fields coming in, will have a lots if else statement
Is there a way to solve this?