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()
?
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.
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.
format() Return Value The format() function returns a formatted representation of a given value specified by the format specifier.
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".
print('Two pair, {0}s and {1}s'.format(*cards))
You are missing only the star :D
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With