0

Currently I am trying to output some data from an SQLite database file into a command line but the data does not seem to be displaying correctly.

Currently when I input for the data to be displayed it outputs it like this:

   Student Table
StudentID    Name    Year                
    1        Dan      13
    2       Jake      13
    3        Joe      13
    4      David      13

I would like all of the names to be in line correctly or at least centered but I cannot figure out how to do it!

The code for the formatting is as follows:

def view():
  con = lite.connect('records.db')
  with con:
      cur = con.cursor()    
      cur.execute('SELECT * FROM Student')
      col_names = [cn[0] for cn in cur.description]
      rows = cur.fetchall()
      print("%20s" % ("Student Table"))
      print("{0:1} {1:^10} {2:20}".format(col_names[0], col_names[1], col_names[2]))
      for row in rows:    
          print("%5s %10s %7s" % (row))
  display = menu.Menu.DisplayMenu("Student")
  choice = GetMenuChoice()
  ValidateMenuChoice(choice)
  main(choice)

any help would be greatly appreciated!

1 Answers1

0

It would probably be a good idea for you to standardise on new-style formatting (str.format instead of %) throughout your code, instead of mixing and matching. That would change, in particular, this line:

print("%5s %10s %7s" % (row))

to this:

print("{:5} {:10} {:7}".format(*row))

You can then adjust that format string to give you alignments. This:

print("{:>5} {:>10} {:>7}".format(*row))

will right-align all three columns. The '>' means 'right-align this field' - you can drop it from the other two columns if you want to leave them with the default alignment.

You're already doing something like this for the column headings, except that you centre the middle one instead of right-aligning it. You could reuse that string for the same effect here:

print("{:5} {:^10} {:7}".format(*row))

(note that the numbers before the : are optional). For less code repetition, you could store that string in a variable and do this:

columns = "{:5} {:10} {:7}"
# get col_names
print("{:20}".format("Student Table")
print(columns.format(*col_names))
for row in rows:
   print(columns.format(*row))
lvc
  • 34,233
  • 10
  • 73
  • 98
  • Thank you this is very helpful! Finally is a lot easier to code the formatting! EDIT: did ask another question, figured it out! –  Dec 05 '13 at 15:12