Print results in MySQL format with Python

前端 未结 5 514
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:21

What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like tha

5条回答
  •  [愿得一人]
    2020-12-05 01:51

    The data is in some list it seems, and are printing the header. Consider some formatting like this:

    res = ['trebuchet ms', 8868, 417]
    res = ['lucida sans unicode', 3525, 116]
    

    and

    print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res))
    

    give you

     trebuchet ms               8868        417
     lucida sans unicode        3525        116
    

    Notice the indexing into the list is done inside the string, format only needs to supply the list or tuple.

    Alternatively, you could specify widths programatically:

    wid1 = 20
    wid2 = 10
    wid3 = 10
    print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3))
    

    which gives identical output as above.

    You'd have to adjust the field widths as required and loop through the list for each line of data instead of made up sample lines. Numbers are automatically right justified, string automatically left.

    Advantage, to some, is of course that this doesn't rely on any external libraries, and is done with what Python already provides.

提交回复
热议问题