Python,打印格式为元组,无法正常工作

时间:2015-02-10 18:05:45

标签: python python-2.7 string-formatting

以下是代码:

#! /usr/bin/python

def goodDifference(total, partial, your_points, his_points):

    while (total - partial >= your_points - his_points):
        partial = partial+1
        your_points = your_points+1

        return (partial, your_points, his_points)

def main():
     total = int(raw_input('Enter the total\n'))
     partial = int(raw_input('Enter the partial\n'))
     your_points = int(raw_input('Enter your points\n'))
     his_points = int(raw_input('Enter his points\n'))
     #print 'Partial {}, yours points to insert {}, points of the other player {}'.format(goodDifference(total, partial, your_points, his_points))
     #print '{} {} {}'.format(goodDifference(total, partial, your_points, his_points))
     print goodDifference(total, partial, your_points, his_points)

if __name__ == "__main__":
     main()

两个带注释的print-with-format不起作用,执行时会报告此错误:IndexError: tuple index out of range。 最后一个打印(未注释),工作正常。 我在Python中阅读了许多格式字符串的例子,我无法理解为什么我的代码无效。

我的python版本是2.7.6

2 个答案:

答案 0 :(得分:4)

str.format()需要单独的参数,并且您将元组作为单个参数传递。因此,它将元组替换为第一个{},然后没有剩余的项目留给下一个。print '{} {} {}'.format(*goodDifference(total, partial, your_points, his_points)) 。要将元组作为单独的参数传递,unpack它:

{{1}}

答案 1 :(得分:2)

为什么不打印元组中的值?

t = goodDifference(total, partial, your_points, his_points)
print '{', t[0], '} {', t[1], '} {', t[2], '}'