为什么我不能使用元组作为新样式(“string”.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.