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 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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))

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.