为什么我不能用元组作为参数,在新的样式,格式器(“串” .format())? 它工作在旧式(“串”%)的罚款?
此代码的工作:
>>> 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.
这并不:
>>> 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'
即使{!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
虽然它的工作原理与方式:
>>> 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.