新しいスタイル( "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.
+1変数の名前を変更します。 –
@Volatility私は{:d}は必要ないと思います。データを注文したい場合は{0} {1} {2} – GeoStoneMarten
@GeoStoneMartenの中の{{d}}を使って簡単に{}を使うか、そこに10進数を入れたい(あなたのコードを読んでいる誰かのために) – Petzku