4

我正在使用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]不行?它们都是同一类型,为什么不通过切片而不显式格式化切片中的每个项目呢?

4

3 回答 3

6

字符串插值需要元组参数的每个元素的格式代码。您可以改为使用.format字符串的新方法:

>>> dealer = ('A','J','K')
>>> print 'Dealer has {} showing'.format(dealer[:2])
Dealer has ('A', 'J') showing

但请注意,使用一个参数,您可以获得打印的元组的字符串表示形式,以及括号和逗号。您可以使用元组解包来单独发送参数,但是您需要两个格式占位符。

>>> print 'Dealer has {} {} showing'.format(*dealer[:2])
Dealer has A J showing

从 Python 3.6 开始,有 f-strings。表达式可以放在花括号中:

>>> dealer = ('A','J','K')
>>> print(f'Dealer has {dealer[0]} {dealer[1]} showing')
Dealer has A J showing
于 2012-08-24T01:45:51.083 回答
5

切片没有任何问题。传递元素数量不正确的元组文字时,您会遇到相同的错误。

"Dealer has %s showing." % self.dealer[:2]

是相同的:

"Dealer has %s showing." % (self.dealer[0], self.dealer[1])

这显然是一个错误。

因此,如果您想在self.dealer[:2]不解包元组的情况下进行格式化:

"Dealer has %s showing." % (self.dealer[:2],)
于 2012-08-24T01:44:24.053 回答
3

您的错误源于在第二次格式化操作中,您传递的参数数量不正确。

"dealer has %s %s showing" % self.dealer[:2]

或者

"dealer has %s showing" % list(self.dealer[:2])

或者

"dealer has %s showing" % self.dealer[0] #or self.dealer[1]

它与不使用元组文字无关。

于 2012-08-24T01:39:28.220 回答