我正在使用python2.7,我想知道pythons字符串插值背后的原因是什么。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]
不行?它们都是同一类型,为什么不通过切片而不显式格式化切片中的每个项目呢?