Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect column alignment when printing table in Python using tab characters

Tags:

python

I want to print a table with some labels on the top. When the labels have a short length, everything is fine; but when the labels are long, the columns do not match up!

I am using tab characters to make space. Here is the code:

table = """
\tX Coordinate\tY Coordinate\tResult
\t00\t00\t00
\t00\t00\t00
\t00\t00\t00
"""
print(table)

Output:

X Coordinate    Y Coordinate    Result
00      00      00
00      00      00
00      00      00

As you can see, Y Coordinate has been pushed out by X Coordinate! How do I make it match up!

like image 377
Bill Avatar asked Oct 16 '25 04:10

Bill


1 Answers

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

Keep in mind that you have to install this using e.g. pip install tabulate

from tabulate import tabulate

print tabulate([[00, 00, 00], [00, 00, 00], [00, 00, 00]], headers=['X Coordinate','Y Coordinate','Result'], tablefmt='orgtbl')

Or use your original table with this code:

alignment = len(max(table.split("\t")))+1
    
for line in table.strip().split("\n"):
    row ="{{:>{}}}".format(alignment) * len(line.strip().split("\t"))
    print row.format(*line.strip().split("\t"))
like image 153
Fourier Avatar answered Oct 17 '25 17:10

Fourier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!