2011-12-10 57 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以上的花括號中的數字,如果按順序出現,可以省略。 –