Python,以元组格式打印,无效

Python, print with format a tuple, not working

代码如下:

#! /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

str.format() 需要单独的参数,并且您将元组作为 单个 参数传递。因此,它将元组替换为第一个 {} ,然后没有更多的项目留给下一个。要将元组作为单独的参数传递,unpack 它:

print '{} {} {}'.format(*goodDifference(total, partial, your_points, his_points))

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

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