Reputation: 57
I am attempting to make a python script that prints out a multiplication table for two inputted integers. I'm pretty much done but I have a small formatting issue that I am having trouble resolving. This is what it outputs currently:
Start of table 27
End of table 33
| 27 | 28 | 29 | 30 | 31 | 32 | 33
27 | 729 : 756 : 783 : 810 : 837 : 864 : 891 :
28 | 756 : 784 : 812 : 840 : 868 : 896 : 924 :
29 | 783 : 812 : 841 : 870 : 899 : 928 : 957 :
30 | 810 : 840 : 870 : 900 : 930 : 960 : 990 :
31 | 837 : 868 : 899 : 930 : 961 : 992 : 1023 :
32 | 864 : 896 : 928 : 960 : 992 : 1024 : 1056 :
33 | 891 : 924 : 957 : 990 : 1023 : 1056 : 1089 :
As you can see in the image each row in the table has a ":" after each integer. This is from this for loop:
for i in range(start,end+1):
print("%5d |"%i,end="")
for j in range(start,end+1):
print("%6d"%(i*j),":",end="")
print()
As you can see in line 4, I have the string ":" which adds the colon after each integer. The problem is I don't want it to add it on the last number for every row. How do I solve this?
Thank you
Upvotes: 1
Views: 1600
Reputation: 90
You must verify in the second if the iteration is equal to the last one, if so, the separated variable is cleaned:
for i in range(start,end+1):
print("%5d |"%i)
for j in range(start,end+1):
separation = ":"
if j == end:
separation = ""
print("%6d"%(i*j),separation)
print()
Upvotes: 0
Reputation: 139
You could try utilising str.join()
to insert your separator between values:
for i in range(start, end+1):
print("%5d |"%i,end="")
row = ["%6d "%(i*j) for j in range(start,end+1)]
print(':'.join(row))
This method saves you having to write extra code to handle the last case differently.
https://www.tutorialspoint.com/python/string_join.htm
Upvotes: 1
Reputation: 560
You could take the last one out of the loop :
for i in range(start,end+1):
print("%5d |"%i,end="")
for j in range(start,end):
print("%6d"%(i*j),":",end="")
print("%6d"%(i*end))
Upvotes: 0
Reputation: 36
for i in range(start,end+1):
print("%5d |"%i,end="")
for j in range(start,end):
print("%6d"%(i*j),":",end="")
print("%6d" % (i * end))
Upvotes: 0