views:

299

answers:

2

Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter and then pass them to the string method. My code looks something like this:

class PairEvaluator(HandEvaluator):
  def returnArbitrary(self):
    return ('ace', 'king')

pe = PairEvaluator()
cards = pe.returnArbitrary()
print('Two pair, {0}s and {1}s'.format(cards))

When I try to run this code, the compiler gives an IndexError: tuple index out of range.

How should I structure my return value to pass it as an argument to .format()?

+1  A: 

This attempts to use "cards" as single format input to print, not the contents of cards.

Try something like;

print('Two pair, %ss and %ss' % cards)

Andrew Grant
+12  A: 
print('Two pair, {0}s and {1}s'.format(*cards))

You are missing only the star :D

Bartosz Radaczyński
That's awesome. What's the definition of the * operator in this context?
Jekke
It unpacks the tuple, for example from "(a, b, c)" to "a, b, c".
Nikhil Chelliah