我如何连接' str'和' int'对象?

时间:2015-10-18 14:57:27

标签: python string concatenation

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

4 个答案:

答案 0 :(得分:1)

使用int强制str并使用str.format将其添加到您的字符串中:

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

答案 1 :(得分:1)

我们可以通过将age转换为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)

答案 2 :(得分:0)

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

答案 3 :(得分: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