我正在使用Python 2.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
我发现需要修改第四行代码,这是引起错误的地方,将其修改为:
print "Dealer has %s %s showing." % self.dealer[:2]
使用两个%s
运算符,一个用于元组切片中的每个项目。当我检查这行代码时,我添加了一个print type(self.dealer[:2])
,并得到以下输出:
<type 'tuple'>
正如我所料,为什么像Player has %s and total %d." % (self.player,self.player_total)
这样的未切片元组可以很好地格式化,而像self.dealer[:2]
这样的切片元组却不行呢?它们都是相同类型的,为什么不能直接传递切片,而需要显式地格式化切片中的每个项呢?
.format
做的这个是Python3中通常的方法,对吧? - tijko{}
,而是使用{0}
表示位置参数的放置。在新代码中,推荐使用.format
。 - Mark Tolonen