2015-10-18 94 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工作

相关问题