【问题标题】:Return a tuple of arguments to be fed to string.format()返回要馈送到 string.format() 的参数元组
【发布时间】:2009-02-11 22:10:10
【问题描述】:

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

【问题讨论】:

    标签: python string-formatting tuples


    【解决方案1】:
    print('Two pair, {0}s and {1}s'.format(*cards))
    

    你只缺少星星 :D

    【讨论】:

    • 太棒了。在这种情况下 * 运算符的定义是什么?
    • 它解包元组,例如从 "(a, b, c)" 到 "a, b, c"。
    • 非常感谢!这是一种更简单的方法,而且帮助很大。
    【解决方案2】:

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

    用 * 解包元组——或用 ** 解压 dict——也比修改格式字符串要简单得多。

    【讨论】:

      【解决方案3】:

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

      尝试类似:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多