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!
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With