私はpython2.7を使用していますが、タプルによるpythonの文字列補間の背後にある理由が何であるか疑問に思っていました。TypeErrors
この小さなコードを実行するときに、私は追いついていました:
def show(self):
self.score()
print "Player has %s and total %d." % (self.player,self.player_total)
print "Dealer has %s showing." % self.dealer[:2]
版画:
Player has ('diamond', 'ten', 'diamond', 'eight') and total 18
Traceback (most recent call last):
File "trial.py", line 43, in <module>
Blackjack().player_options()
File "trial.py", line 30, in player_options
self.show()
File "trial.py", line 27, in show
print "Dealer has %s showing." % (self.dealer[:2])
TypeError: not all arguments converted during string formatting
そのため、エラーの発生元である 4 行目を次のように変更する必要があることがわかりました。
print "Dealer has %s %s showing." % self.dealer[:2]
%s
タプル スライスの各項目に 1 つずつ、2 つの演算子を使用します。この行で何が起こっているのかを調べていたときに、 a を追加したところ、次のprint type(self.dealer[:2])
ようになりました。
<type 'tuple'>
私が予想したように、スライスされていないタプルのようなPlayer has %s and total %d." % (self.player,self.player_total)
形式はうまくいき、スライスされたタプルself.dealer[:2]
はうまくいかないのはなぜですか? それらは両方とも同じ型ですが、スライス内のすべての項目を明示的にフォーマットせずにスライスを渡さないのはなぜですか?