Python, table printing

Python, table printing

Published May 21, 2015 in Development - Last update on July 6, 2015.

I always self-asked me how is the code used by mysql command for print tables. I ever don't know but I know how to do that in Python: With Format Specification Mini-Language.

Print a table

A script of my idea looks like this:

GUYS = ['tony', 'joe', 'ugo']
ROW_FORMAT = '| {0:5} | {1:30} |'

print(ROW_FORMAT.format('ID', 'NAME')) # table head for i, name in enumerate(GUYS): # get an ID for each guy print(ROW_FORMAT.format(i, name))

I use a string, ROW_FORMAT, as a template for produce rows. With this kind of template variable are rendered with brackets ({...}). Result of the script above is:

| ID    | NAME                           |
|     0 | tony                           |
|     1 | joe                            |
|     2 | ugo                            |

The useful thing made is fill string for adjust all rows' width. ID has 5 characters ({0:5}) and NAME 30 {{1:30}). 

Align text

By default, integers are right-aligned and strings are left-aligned. This behavior can be change with < (left), > (right) or ^ (center) before width. If I change ROW_FORMAT string like below:

ROW_FORMAT = '| {0:<5} | {1:<30} |'

I simply add < and all is done. Result of the script above is:

| ID    | NAME                           |
| 0     | tony                           |
| 1     | joe                            |
| 2     | ugo                            |

 

Reference

Comments

  • price metoclopramide zamienniki

    price metoclopramide zamienniki on 04/01/2018 11:25 a.m. #

    When someone writes an paragraph he/she maintains the thought of a user in his/her brain that how a user can know it.
    So that's why this article is great. Thanks!

  • loans online no credit check

    loans online no credit check on 04/01/2018 3:25 p.m. #

    best online loans instant approval
    loans online application
    online loans direct lenders
    loans online only

Post your comment

Comment as . Log out.