Marmstrong
Marmstrong

Reputation: 1786

Python: Formatting multiple values in .format

I tried to use the following statements in a bit of python code. The formatting worked, however, it used the value of current image in all of the placeholders. Why is this the case? If I remove the current image it does the same with expected_time.

print expected_time

print "Frame No. {0:06d} Expected: {0:.3f}ms Actual: {0:.3f}ms Difference: {0:.3f}ms".format(currentImage, expected_time, regression_obj.timeFromStart, abs(expected_time - regression_obj.timeFromStart))

OUTPUT:

Frame No. 000001 Expected: 1.000ms Actual: 1.000ms Difference: 1.000ms - ERROR

Upvotes: 0

Views: 2115

Answers (2)

Azwr
Azwr

Reputation: 784

This would work :

print "Frame No. {0:06d} Expected: {1:.3f}ms Actual: {2:.3f}ms Difference:{3:.3f}ms".format(currentImage, expected_time, regression_obj.timeFromStart, abs(expected_time - regression_obj.timeFromStart))

Your code does not work because you are assigining every placeholder the value 0 which corresponds to CurrentImage .

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

You're using 0 in all of the specifiers, so it only prints the value of the item at 0th position:

{0:06d} 
 ^

In Python 2.7+ you can remove it completely and for Python 2.6 you need to specify the position manually. (From docs: Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.)

For Python 2.7+:

print "Frame No. {:06d} Expected: {:.3f}ms Actual: {:.3f}ms Difference: {:.3f}ms".format(...)

For Python 2.6:

print "Frame No. {0:06d} Expected: {1:.3f}ms Actual: {2:.3f}ms Difference: {3:.3f}ms".format(...)

Upvotes: 3

Related Questions