返回要传递给string.format()的参数元组

Yes*_*ke. 34 python tuples string-formatting

目前,我正在尝试在Python中获取一个方法,以返回一个零个,一个或两个字符串的列表,以插入字符串格式化程序,然后将它们传递给字符串方法.我的代码看起来像这样:

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

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

当我尝试运行此代码时,编译器会将IndexError:tuple索引超出范围.
我应该如何构造我的返回值以将其作为参数传递给.format()

Bar*_*ski 76

print('Two pair, {0}s and {1}s'.format(*cards))
Run Code Online (Sandbox Code Playgroud)

你只缺少明星:D

  • 它将元组解包,例如从"(a,b,c)"解包为"a,b,c". (16认同)
  • 棒极了.在这种情况下,*运算符的定义是什么? (5认同)

tro*_*jer 5

格式优先于 % 运算符,因为它在 Python 2.6 中被引入:http : //docs.python.org/2/library/stdtypes.html#str.format

用 * 或带 ** 的 dict 解包元组也简单得多,而不是修改格式字符串。