Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
Yes - that Jake. Avatar asked Feb 11 '09 22:02

Yes - that Jake.


People also ask

How do you return a tuple to a string?

Use the str. join() Function to Convert Tuple to String in Python. The join() function, as its name suggests, is used to return a string that contains all the elements of sequence joined by an str separator. We use the join() function to add all the characters in the input tuple and then convert it to string.

What is format () function in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is return type for function format () is?

format() Return Value The format() function returns a formatted representation of a given value specified by the format specifier.

How do you format a tuple in Python?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".


2 Answers

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

You are missing only the star :D

like image 72
Bartosz Radaczyński Avatar answered Sep 18 '22 13:09

Bartosz Radaczyński


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.

like image 28
trojjer Avatar answered Sep 18 '22 13:09

trojjer