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

时间:2009-02-11 22:10:10

标签: python string-formatting tuples

目前,我正在尝试在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))

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

3 个答案:

答案 0 :(得分:75)

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

你只缺少明星:D

答案 1 :(得分:4)

格式比%运算符更受欢迎,因为它在Python 2.6中引入:http://docs.python.org/2/library/stdtypes.html#str.format

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

答案 2 :(得分:1)

这会尝试使用“卡片”作为打印的单一格式输入,而不是卡片的内容。

尝试类似:

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