I'm using python2.7 and I was wondering what the reasoning is behind pythons string interpolation with tuples. I was getting caught up with TypeErrors
when doing this small bit of code:
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]
Prints:
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
So I found that I needed to change the fourth line where the error was coming from, to this:
print "Dealer has %s %s showing." % self.dealer[:2]
With two %s
operators, one for each item in the tuple slice. When I was checking out what was going on with this line though I added in a print type(self.dealer[:2])
and would get:
<type 'tuple'>
Like I expected, why would a non-sliced tuple like the Player has %s and total %d." % (self.player,self.player_total)
format fine and a sliced tuple self.dealer[:2]
not? They're both the same type why not pass the slice without explicitly formatting every item in the slice?
String interpolation requires a format code for each element of the tuple argument. You could instead use the new .format
method of strings:
>>> dealer = ('A','J','K')
>>> print 'Dealer has {} showing'.format(dealer[:2])
Dealer has ('A', 'J') showing
But note that with one argument you get the string representation of the tuple printed, along with parentheses and commas. You can use tuple unpacking to send the arguments separately, but then you need two format placeholders.
>>> print 'Dealer has {} {} showing'.format(*dealer[:2])
Dealer has A J showing
As of Python 3.6, there are f-strings. Expressions can be placed into the curly braces:
>>> dealer = ('A','J','K')
>>> print(f'Dealer has {dealer[0]} {dealer[1]} showing')
Dealer has A J showing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With