tij*_*jko 4 python tuples string-interpolation
我正在使用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]
Run Code Online (Sandbox Code Playgroud)
打印:
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
Run Code Online (Sandbox Code Playgroud)
所以我发现我需要更改错误来自的第四行,以此:
print "Dealer has %s %s showing." % self.dealer[:2]
Run Code Online (Sandbox Code Playgroud)
使用两个%s运算符,一个元组用于元组切片中的每个项目.当我查看这条线路发生了什么,虽然我添加了一个print type(self.dealer[:2])并且会得到:
<type 'tuple'>
Run Code Online (Sandbox Code Playgroud)
就像我预期的那样,为什么非切片元组会像Player has %s and total %d." % (self.player,self.player_total)格式好而切片元组self.dealer[:2]不是?它们都是相同的类型,为什么不通过切片而不显式格式化切片中的每个项目?
字符串插值需要元组参数的每个元素的格式代码.您可以使用新.format的字符串方法:
>>> dealer = ('A','J','K')
>>> print 'Dealer has {} showing'.format(dealer[:2])
Dealer has ('A', 'J') showing
Run Code Online (Sandbox Code Playgroud)
但请注意,使用一个参数,您将获得打印元组的字符串表示形式,以及括号和逗号.您可以使用元组解包来单独发送参数,但是您需要两个格式占位符.
>>> print 'Dealer has {} {} showing'.format(*dealer[:2])
Dealer has A J showing
Run Code Online (Sandbox Code Playgroud)
从Python 3.6开始,有f字符串.表达式可以放在花括号中:
>>> dealer = ('A','J','K')
>>> print(f'Dealer has {dealer[0]} {dealer[1]} showing')
Dealer has A J showing
Run Code Online (Sandbox Code Playgroud)
切片没有问题.传递元组数量不正确的元组文字时会出现相同的错误.
"Dealer has %s showing." % self.dealer[:2]
Run Code Online (Sandbox Code Playgroud)
是相同的:
"Dealer has %s showing." % (self.dealer[0], self.dealer[1])
Run Code Online (Sandbox Code Playgroud)
这显然是一个错误.
所以,如果你想在self.dealer[:2]没有元组拆包的情况下进行格式化:
"Dealer has %s showing." % (self.dealer[:2],)
Run Code Online (Sandbox Code Playgroud)