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

1
  • I'd just suggest something like this 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. Commented May 30, 2020 at 11:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.