2015-12-15 27 views
0

我正在做這個教程,我遇到了這個奇怪的錯誤。我打印日期。爲什麼我得到這個python連接錯誤?

因此,樣本代​​碼之前,你需要有:

from datetime import datetime 
now = datetime.now() 

這將打印

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year) 

那麼這將會

print "pizza" + "pie" 

所以將這個

print "%s/%s/%s" % (now.month, now.day, now.year) 

但是,當我介紹串聯運營商:

#Traceback (most recent call last): 
# File "python", line 4, in <module> 
#TypeError: not all arguments converted during string formatting 
print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year) 

它的某種級聯問題。我不明白的是代碼將在我連接其他字符串時以及當我不使用與我想要的字符串串聯時打印。

+1

因爲它試圖所有值格式化到最後'「%S」'。你需要用parens來包裝字符串。 –

+1

這是一個運算符優先級的簡單問題 – njzk2

回答

2

你是運算符優先級引起的遇到的問題。

以下行可行,因爲這是string literal concatenation,它的優先級高於%運算符。

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year) 

下列不工作,因爲+操作符比%運算符的優先級低。

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year) 

要解決它,所以它首先被執行加括號拼接,就像這樣:

print ("%s" + "/" + "%s" + "/" + "%s") % (now.month, now.day, now.year) 
+0

我接受了這個,因爲儘管第一個答案幫助我解決了這個問題,但解釋更加徹底,儘管我自己看了一會兒,卻花了一段時間。當我擁有1個權力時,我會加1個第一個答案。 – user3452783

5

正因爲如此:

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year) 

是與此相同,由於operator precedence(注意額外的括號)

print "%s" + "/" + "%s" + "/" + ("%s" % (now.month, now.day, now.year)) 
+0

我沒有關注。這是拋出它的優勢,另外有更高的優先?不應該這樣做,因爲它假設它們正在被「打印」%s「」/「」%s「」/「」%s「%(now.month,now.day,now.year) 級聯?認爲你可以多解釋一下? – user3452783

+0

再想一想,我現在明白了。空格實際上不會將這些字符串連接在一起,而只是將這些字符串打印在一起。附加標誌作爲運營商以及百分比符號,並將其順序混淆。 – user3452783