36

目前,我正在尝试在 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 index out of range。
我应该如何构造我的返回值以将其作为参数传递给.format()

4

3 回答 3

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

你只缺少星星:D

于 2009-02-11T22:20:47.640 回答
5

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

只需使用 * 解压缩元组 - 或使用 ** 解压缩 dict - 而不是修改格式字符串也简单得多。

于 2012-11-27T10:29:51.203 回答
1

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

尝试类似:

print('Two pair, %ss and %ss' % cards)
于 2009-02-11T22:20:26.160 回答