Python string interpolation using tuple fragments?

I am using python2.7, and I was wondering what the argument is for interpolating pythons strings with tuples. When I was doing this little bit of code, I was getting 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] 

Print

 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 need to change the fourth line where the error came from:

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

With two %s statements, one for each item in the collection piece. When I checked what happens with this line, although I added to print type(self.dealer[:2]) and would get:

 <type 'tuple'> 

As I expected, why not a sliced ​​tuple like the Player has %s and total %d." % (self.player,self.player_total) format Player has %s and total %d." % (self.player,self.player_total) , and a sliced ​​tuple self.dealer[:2] not? They are both of the same type , so don't skip a slice without explicitly formatting each element in the slice?

+4
source share
3 answers

Nothing happens with a piece. You will get the same error when passing a string literal with the wrong number of elements.

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

matches with:

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

This is obviously a mistake.

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

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

Interpolation of strings requires a formatting code for each element of the tuple argument. Instead, you can use the new .format method for 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 a string representation of the printed tuple along with round and commas. You can use decompression to send arguments separately, but then you need two format placeholders.

 >>> print 'Dealer has {} {} showing'.format(*dealer[:2]) Dealer has AJ showing 
+5
source

Your mistake is due to the fact that in the second formatting operation you are passing the wrong number of arguments.

Do

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

or

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

or

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

This has nothing to do with not using the tuple literal.

+3
source

All Articles