2011-12-10 54 views
2
print 'For ' + str(n) ' total pieces:\n' + str(a) + ' six pieces, ' + str(b) + ' nine pieces, ' + str(c) + ' twenty pieces' 

时解释说,有一个语法错误,并突出了'\n语法错误使用 n

+0

投票结果太过本地化,因为“太本地化”的说法说这个问题不太可能帮助其他任何人。 –

回答

4

有一个+str(n)后直接下落不明。编译器突出显示导致解析错误的标记结束。在这种情况下,编译器并不期望在函数调用str(n)之后直接输入字符串。

1

' total pieces:\n'之前缺少一个“+”。

虽然如此,作为一个格式化的字符串,这会更好。

print "For %(total)f total pieces:\n%(six)f six pieces, %(nine)f nine pieces, %(twenty)f twenty pieces" % { 
    "total": n, 
    "six": a, 
    "nine": b, 
    "twenty": c 
} 
0

你缺少一个+' total pieces:\n'

print 'For ' + str(n) + ' total pieces:\n' + str(a) + ' six pieces, ' + str(b) + ' nine pieces, ' + str(c) + ' twenty pieces' 
0

在缺少+

print 'For ' + str(n) + ' total pieces:\n' + str(a) + ' six pieces, ' + str(b) + ' nine pieces, ' + str(c) + ' twenty pieces' 
        ^
2

对于文本,如在一个问题中,它的使用格式化字符串是一个好主意,它甚至有助于防止像你遇到的错误(缺少+):

'For %d total pieces:\n%d six pieces, %d nine pieces, %d twenty pieces' % (n,a,b,c) 

在上面的代码片段中,我假设n,a,b,c是数字。有关更多信息,请参阅文档中的String Formatting Operations

+1

如果你要学习字符串格式化系统,我建议学习[new one](http://docs.python.org/library/string.html#format-string-syntax)而不是[old one] ](http://docs.python.org/library/stdtypes.html#string-formatting)Óscar在上面的答案中使用。这里是你如何做到这一点:''{0}总件:\ n {1}六件,{2}九件,{3}二十件'.format(n,a,b,c) '。对于2.7以上的花括号中的数字,如果按顺序出现,可以省略。 –