0

I am creating a table of data in Python to print on the console using the code below:

print("Model Results:\n")
print("R&D Spend\tAdministration\tMarketing Spend\tState\tPredicted Profit")
for i in range(50):
    print("%0.2f\t%0.2f\t%0.2f\t%d\t%0.2f"%(
        X_test[i][0],X_test[i][1],X_test[i][2],X_test[i][3], y_predict[i]))

The trouble is some of the rows are not displaying correctly (highlighted in the attached screenshot). This seems to happen for rows where the first column is 4 figures. What trick can I use to overcome this?

This is the console output with my table:

Console output with my table

Majid Roustaei
  • 1,556
  • 1
  • 20
  • 39
LindaniB
  • 53
  • 5
  • I'd just suggest something like this https://stackoverflow.com/a/26937531/10039400. The problem is the tab characters you are setting in your print. When words are different in length the tab will be placed at different positions and that results in weird formatting. Using a library is probably the easiest way if you dont want to handle everything by hand. – DJSchaffner May 30 '20 at 11:21

1 Answers1

2

This can be easily done with format:

def print_row(*args):
    print((len(args) * '{:<15.3f}').format(*args))

In {:<15.3f} 15 is width of column and 3 is number of digits after decimal point. (Omit the < for right alignment.) This way you don't need to use tabs.

alani
  • 12,573
  • 2
  • 13
  • 23