Why can't I use tuple as argument to formatter in new style ("string".format())? It works fine in old style ("string" %)?
This code works:
>>> tuple = (500000, 500, 5) ... print "First item: %d, second item: %d and third item: %d." % tuple First item: 500000, second item: 500 and third item: 5.
And this doesn't:
>>> tuple = (500000, 500, 5) ... print("First item: {:d}, second item: {:d} and third item: {:d}." ... .format(tuple)) Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: Unknown format code 'd' for object of type 'str'
Even with {!r}
>>> tuple = (500000, 500, 5) ... print("First item: {!r}, second item: {!r} and third item: {!r}." ... .format(tuple)) Traceback (most recent call last): File "<stdin>", line 2, in <module> IndexError: tuple index out of range
Though it works with that way:
>>> print("First item: {!r}, second item: {!r} and third item: {!r}." ... .format(500000, 500, 50)) First item: 500000, second item: 500 and third item: 5.
The old way of formatting used a binary operator, %
. By its nature, it can only accept two arguments. The new way of formatting uses a method. Methods can take any number of arguments.
Since you sometimes need to pass multiple things to format and it's somewhat clumsy to create tuples with one item all the time, the old-style way came up with a hack: if you pass it as a tuple, it will use the contents of the tuple as the things to format. If you pass it something other than a tuple, it will use that as the only thing to format.
The new way does not need such a hack: as it is a method, it can take any number of arguments. As such, multiple things to format will need to be passed as separate arguments. Luckily, you can unpack a tuple into arguments using *
:
print("First item: {:d}, second item: {:d} and third item: {:d}.".format(*tuple))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With