Python Tables

tableI was asked in class how we can create a table in Python. There are a number of ways to do this but the easiest is probably to use the .format method.

The program reads in data from a CSV file before displaying the information in a two column table. There is a lot of internal commentary you can strip out leaving just the code.

The main part of the program is line 28. Where the contents of names and scores are displayed one line at a time with padding to make them appear to be in a table.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#Read in 10 sets of data from a CSV File

names=[""]*10
scores=[0]*10
csv_file = open('highscores.csv','r')   # 1. Open file
for index in range(10):                 # 2. read data from file
    names[index],scores[index]=csv_file.readline()[:-1].split(',')     # split into two variables after removing newline
    scores[index]=int(scores[index])    # change score to Integer
csv_file.close()                        # 3. close file

# Using format method to justify the coloumns
# .format is used to change the format of a string
# eg.    '{:<5}{:>10}'.format('Name','Score')
#          1st   2nd            1st    2nd
# < left align
# > right align
# ^ centre align
# the number is the size the string is padded too
# the above example would create a string like the one below A is used for a 1st, B for 2nd
# AAAAABBBBBBBBBB
# so Dan and 2343 would give
# DanAABBBBBB2343 where AABBBBBB would be spaces

print('{:*^15}'.format('High Scores')) # The * is used instead of spaces for padding
print('-'*15) # 15 dashes
print('{:<5}{:>10}'.format('Name','Score')) # Print the headings (outside of loop)
for index in range(10):
    print('{:<5}{:>10}'.format(names[index],scores[index])) # display each line
    

 

Leave a Reply

Your email address will not be published. Required fields are marked *