lysov
lysov

Reputation: 160

Python 3.5 String formatting

How to align to the left the row with percentages, so the output look nice?

The problem seems to be in the following line:

print("{:>9}%".format(i*10), end='')

Sample input and output of the program:

How many columns should there be (1-6) ? 4
How many rows should there be in the table? 5
Original   Price discounted by
   price       20%       30%       40%       50%
    5.00     4.00    3.50    3.00    2.50 
   10.00     8.00    7.00    6.00    5.00 
   15.00    12.00   10.50    9.00    7.50 
   20.00    16.00   14.00   12.00   10.00 
   25.00    20.00   17.50   15.00   12.50 

The goal:

How many columns should there be (1-6) ? 4
How many rows should there be in the table? 5
Original   Price discounted by
   price      20%     30%     40%     50%
    5.00     4.00    3.50    3.00    2.50 
   10.00     8.00    7.00    6.00    5.00 
   15.00    12.00   10.50    9.00    7.50 
   20.00    16.00   14.00   12.00   10.00 
   25.00    20.00   17.50   15.00   12.50 

The code:

column = int(input("How many columns should there be (1-6) ? "))
row = int(input("How many rows should there be in the table? "))

initialPrice = 5.00
initialDiscount = 10.0

print("{0:>8} {1:>21}".format("Original", "Price discounted by"))
print("{0:>8}".format("price"), end='')
for i in range(2,column+2):
    print("{:>9}%".format(i*10), end='')
print()

for y in range (1,row+1):
    print("{0:>8.2f} ".format(y * initialPrice), end='')
    for x in range (2,column+2):
        print("{0:>8.2f}".format(y * initialPrice * (1 - x*0.1)), end='')
    print()

Upvotes: 1

Views: 6064

Answers (1)

Steven Summers
Steven Summers

Reputation: 5394

After a bunch of trial and error I managed to get it. Change this line

print("{0:>8.2f}".format(y * initialPrice * (1 - x*0.1)), end='')

to this. What has changed is the spacing value {0:>8.2f} -> {0:>9.2f} and end is now a string with a space end=' '.

print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end=' ')

Well you can make the spacing value any number you want, it just has to match the value used for the print percentages.

Alternatively, you can have the end=' ' on the print prices

Full Code (Alternate lines are commented in):

column = int(input("How many columns should there be (1-6) ? "))
row = int(input("How many rows should there be in the table? "))

initialPrice = 5.00
initialDiscount = 10.0

print("{0:>8} {1:>21}".format("Original", "Price discounted by"))
print("{0:>8}".format("price"), end='')
#print("{0:>8}".format("price"), end=' ')
for i in range(2,column+2):
    print("{:>9}%".format(i*10), end='')
print()

for y in range (1,row+1):
    print("{0:>8.2f} ".format(y * initialPrice), end='')
    for x in range (2,column+2):
        print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end=' ')
        #print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end='')
    print()

Upvotes: 1

Related Questions