简体   繁体   English

Python中的格式无法正确显示

[英]Formatting in Python not displaying correctly

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. 目前,我正在尝试将一些数据从SQLite数据库文件输出到命令行,但是数据似乎无法正确显示。

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! 任何帮助将不胜感激!

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. 对于您来说,在整个代码中标准化新型格式(用str.format代替% )而不是混合和匹配可能是一个好主意。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM