Search code examples
pythontuplesstring-interpolation

Python string interpolation with tuple slices?


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?


Solution

  • Nothing is wrong with the slice. You would get the same error when passing a tuple literal with incorrect number of elements.

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

    is the same as:

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

    Which is obviously an error.

    So, if you would like to format self.dealer[:2] without tuple unpacking:

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