Yes - that Jake.
Yes - that Jake.

Reputation: 17121

Return a tuple of arguments to be fed to string.format()

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()?

Upvotes: 36

Views: 15703

Answers (3)

Andrew Grant
Andrew Grant

Reputation: 58786

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)

Upvotes: 1

trojjer
trojjer

Reputation: 639

Format is preferred over the % operator, as of its introduction in Python 2.6: http://docs.python.org/2/library/stdtypes.html#str.format

It's also a lot simpler just to unpack the tuple with * -- or a dict with ** -- rather than modify the format string.

Upvotes: 5

Bartosz Radaczyński
Bartosz Radaczyński

Reputation: 18564

print('Two pair, {0}s and {1}s'.format(*cards))

You are missing only the star :D

Upvotes: 86

Related Questions