2015-10-18 96 views
-3
age = raw_input ('How old are you? ') 
print "In two year's time you will be: " , age + 2 

如何獲取此代碼的最後一行工作?當我在Python中運行時出現錯誤TypeError: cannot concatenate 'str' and 'int' objects如何連接'str'和'int'對象?

+0

'age = int(raw_input('你多大了?'))'? –

回答

1

使用要挾intstr,並使用str.format將它添加到您的字符串:

age = int(raw_input ('How old are you? ')) 
print "In two year's time you will be: {}".format(age + 2) 
+0

這仍然會嘗試連接一個字符串和一個int。 – interjay

+0

@interjay謝謝,更新。 – agconti

+0

好的,但'str.format'實際上並不是必需的或與此錯誤相關,而您的答案將其作爲解決方案。 – interjay

0
age = int(raw_input ('How old are you? ')) 
print "In two year's time you will be: " , age + 2 
+0

第二個將不起作用。 – interjay

+0

@interjay,是的,有些愚蠢的想法是,你必須首先使你的輸入int()。 – pythad

1

我們可以通過年齡類型轉換成int,然後將它添加到一個int串連它。

age = raw_input ('How old are you? ') 
print "In two year's time you will be: " , int(age) + 2 

逸岸更好的方法來打印這是使用格式:

print "In two year's time you will be: {}".format(int(age) + 2) 
+0

代碼有什麼問題?請提供downvote的解釋。 – blackmamba

+0

哦。對於那個很抱歉。我會牢記這一點。 – blackmamba

0
age = raw_input ('How old are you? ') 
print "In two year's time you will be: " , str(int(age) + 2) 

這應該如果你正在使用Python 2.7的工作,不知道這是否會在3.X工作

相關問題