代码之家  ›  专栏  ›  技术社区  ›  Yes - that Jake.

返回要提供给string.format()的参数元组

  •  33
  • Yes - that Jake.  · 技术社区  · 16 年前

    目前,我正在尝试用Python中的一个方法返回一个包含零个、一个或两个字符串的列表,以插入到字符串格式化程序中,然后将它们传递给string方法。我的代码如下所示:

    class PairEvaluator(HandEvaluator):
      def returnArbitrary(self):
        return ('ace', 'king')
    
    pe = PairEvaluator()
    cards = pe.returnArbitrary()
    print('Two pair, {0}s and {1}s'.format(cards))
    

    当我试着运行这段代码时,编译器给出了一个索引器:元组索引超出范围。
    .format() ?

    3 回复  |  直到 13 年前
        1
  •  84
  •   Bartosz Radaczyński    16 年前
    print('Two pair, {0}s and {1}s'.format(*cards))
    

        2
  •  5
  •   trojjer    10 年前

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

    只需用*-或**解压元组比修改格式字符串简单得多。

        3
  •  1
  •   Delimitry COLD TOLD    9 年前

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

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