0

I am trying to make a table that has borders in Python. It uses a for loop, to iterate row by row. The problem is, if one of the output numbers contains an additional digit, say from 10 to 100, then the borders will maladjust. I am using f-string literals, but if there is a better way I would like to know.

This is the code I am using to print it:

 print(f'|   {month:<2}| {payment:,.2f}  {principle:,.2f}    {interest:,.2f}  |   {balance:,.2f}  |    {total_payments:,.2f}     {total_principle:,.2f}       {total_interest:,.2f} |')

This is what it should look like after a few iterations:

desired result

This is what it actually looks like after a few iterations:

undesired result

I'm not sure if it is relevant to the border question or not, but I also must do indentation properly. I believe I know how to do this already, ex: {x:>6}. Does that effect the borders too?

Asker
  • 1
  • Does this answer your question? [Printing Lists as Tabular Data](https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data) – Tomerikoo Jul 22 '20 at 07:29

1 Answers1

0

You should give the number of positions for each

For example, if you want to print payment, assuming the total string length is 10, give it as {payment:10,.2f}

This should align them correctly. Let me know if this does not work.

print(f'|   {month:<2}| {payment:10,.2f}  {principle:10,.2f}    {interest:10,.2f}  |   {balance:10,.2f}  |    {total_payments:10,.2f}     {total_principle:10,.2f}       {total_interest:10,.2f} |')

Output:

|   3 |    350.39     319.96        30.43  |    9,043.23  |     1,051.17        956.77           94.40 |
|   4 |    350.39     321.00        29.39  |    8,722.23  |     1,401.56      1,277.77          123.79 |

In addition, you can remove the spaces between the close bracket and open bracket } { and instead increase the number 10 to a larger number. It will take care of the alignment.

I updated your print format as follows. You can use this or keep the old one too.

print(f'|   {month:<2} |{payment:8,.2f}{principle:8,.2f}{interest:8,.2f}  |{balance:10,.2f}  |{total_payments:12,.2f}{total_principle:12,.2f}{total_interest:10,.2f} |')


|   3  |  350.39  319.96   30.43  |  9,043.23  |    1,051.17      956.77     94.40 |
|   4  |  350.39  321.00   29.39  |  8,722.23  |    1,401.56    1,277.77    123.79 |
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33