How to Print “Pretty” String Output in Python

后端 未结 4 1693
不知归路
不知归路 2020-12-02 13:31

I have a list of dicts with the fields classid, dept, coursenum, area, and title from a sql query. I would like to output the values in a human readable format. I was thinki

4条回答
  •  孤街浪徒
    2020-12-02 14:08

    Standard Python string formatting may suffice.

    # assume that your data rows are tuples
    template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10
    print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header
    for rec in your_data_source: 
      print template.format(*rec)
    

    Or

    # assume that your data rows are dicts
    template = "{CLASSID:8}|{DEPT:10}|{C_NUM:15}|{AREA:7}|{TITLE:10}" # same, but named
    print template.format( # header
      CLASSID="CLASSID", DEPT="DEPT", C_NUM="COURSE NUMBER", 
      AREA="AREA", TITLE="TITLE"
    ) 
    for rec in your_data_source: 
      print template.format(**rec)
    

    Play with alignment, padding, and exact format specifiers to get best results.

提交回复
热议问题