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

2024-04-27 03:15:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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。你知道吗


Tags: 代码inyouinputagerawtimebe
3条回答

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

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

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

相关问题 更多 >