Dlaczego nie mogę używać tuple jako argumentu do sformatowania w nowym stylu ("string" .format())? Działa dobrze w starym stylu ("ciąg"%)?Nowe formatowanie stylu z krotką jako argumentem
Ten kod działa:
>>> 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.
I to nie:
>>> 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'
Nawet {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
Choć pracuje z tym sposób:
>>> 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 za zmianę nazwy zmiennej. –
@Volatility Myślę, że {: d} nie jest konieczne. Jeśli chcesz zamówić dane, możesz po prostu {} lub podać porządek z indeksem lub danymi w krotce {0} {1} {2} – GeoStoneMarten
@GeoStoneMarten, podczas gdy ja się nieco zgadzam, użycie '{: d}' oznacza wyraźniej, że chcesz mieć tam liczbę dziesiętną (dla kogoś czytającego twój kod) – Petzku