0

I would like to print multiple tables,

following is the line which am using to print,

 print ("%d\t*\t%d\t=\t%2d"%(multiplicand,i,result))

How to specify or pass the values such as two from a variable.

I tried something like this

max_len = len(maxresult)
print ("%d\t*\t%d\t=\t%" +max_len+"d"%(multiplicand,i,result))

but it didn't work.

2 Answers2

1

You can use the * formatter to take the size from the inputs:

multiplicand, i = 50, 2
result= multiplicand * i
max_len = len(str(result))

format = "%d\t*\t%d\t=\t%*d"
print(format % (multiplicand, i, max_len, result))

The * length specifier in %*d takes the next value from the tuple as the length specifier. Note that that is a minimum length, not a maximum.

The str.format() formatting operation lets you do this with any parameter, not just the length; simply use another placeholder for the parameter you want to fill with a formatting value:

format = "{:d}\t*\t{:d}\t=\t{:{}d}"
print(format.format(multiplicand, i, max_len, result))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Did you tried to create the format String before?

multiplicand,i = 50,2
result= multiplicand *i
max_len = 2

format = "%d\t*\t%d\t=\t%" +str(max_len)+ "d"
print (format % (multiplicand,i,result))
xecgr
  • 5,095
  • 3
  • 19
  • 28