爲什麼我不能用元組作爲參數,在新的樣式,格式器(「串」 .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.
1爲重命名的變量中。 – 2013-03-03 04:15:25
@Volatility我認爲{:d}是沒有必要的。如果您想要訂購數據,您可以簡單地使用{}或使用元組{0} {1} {2} – GeoStoneMarten 2016-01-07 09:10:52
@GeoStoneMarten中的索引或數據指定訂單,但我同意使用'{:d}'更清楚地表明您想要一個十進制數字(用於讀取您的代碼的其他人) – Petzku 2016-11-02 11:08:27