Skip to content

Python print table align | Example code

  • by

Use format to print table aligns in Python. Using the .format approach, you could use padding to align all of your strings.

You can also use tabulate module for it.

Python print table align example

Simple example code text formatting rows in Python.

table_data = [
    ['a', 'b', 'c'],
    ['ABC', 'b', 'c'],
    ['a', 'XYZ', 'c']
]
for row in table_data:
    print("{: >5} {: >5} {: >5}".format(*row))

Output:

Python print table align

Another example

header = ['X Coordinate', 'Y Coordinate', 'Result']
row = ['100', '200', '300']
rows = [header, row, row, row]
print('\n'.join([''.join(['{:16}'.format(x) for x in r]) for r in rows]))

Output:

X Coordinate    Y Coordinate    Result          
100             200             300             
100             200             300             
100             200             300     

Or, using f-strings:

print('\n'.join([''.join([f'{x:16}' for x in r]) for r in rows]))

Tabulate

One possible solution is to rely on some package that has been designed for this purpose, like tabulate: Read more about it!

from tabulate import tabulate

print(tabulate([[0, 1, 2], [3, 4, 5], [6, 7, 0]],
               headers=['X', 'Y', 'Z'],
               tablefmt='orgtbl'))

Output:

|   X |   Y |   Z |
|-----+-----+-----|
|   0 |   1 |   2 |
|   3 |   4 |   5 |
|   6 |   7 |   0 |

IF… you do not like the dashes, you can use this instead:

print(tabulate(table, tablefmt="plain"))

How to Print “Pretty” String Output in Python?

Standard Python string formatting may suffice.

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)

Do comment if you have any doubts or suggestions on this Python table topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading