2015-02-10 65 views
0

下面是代码:Python中,打印带有格式的元组,没有工作

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

两个评论打印与格式不工作,执行它报告此错误时:IndexError: tuple index out of range。 最后一次打印(未评论),工作正常。 我已经阅读了很多Python格式字符串的例子,我不明白为什么我的代码不工作。

我的Python版本是2.7.6

回答

4

str.format()需要单独的参数,而你传递一个元组作为说法。因此,它将元组替换为第一个{},然后再没有剩下的项目留给下一个。要通过元组作为单独的参数,它unpack

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

*在这种情况下做什么? – 2015-02-10 18:19:29

+0

将元组解包为多个参数。 https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists – kindall 2015-02-10 18:20:38

+0

现在完美... *此答案很有用* – 2015-02-10 18:22:36

2

为什么你不只是在打印输出元组值是多少?

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