[英]How do I concatenate 'str' and 'int' objects?
age = raw_input ('How old are you? ')
print "In two year's time you will be: " , age + 2
How do I get the last line of this code to work?如何使此代码的最后一行起作用? I get the error TypeError: cannot concatenate 'str' and 'int' objects
when I run it in Python.我收到错误TypeError: cannot concatenate 'str' and 'int' objects
when I run it in Python.
Use coerce the int
to a str
and use str.format to add it to your string:使用强制int
为str
并使用str.format将其添加到您的字符串中:
age = int(raw_input ('How old are you? '))
print "In two year's time you will be: {}".format(age + 2)
We can concatenate it by typecasting age to int and then adding it to an int.我们可以通过将 age 类型转换为 int 然后将其添加到 int 来连接它。
age = raw_input ('How old are you? ')
print "In two year's time you will be: " , int(age) + 2
Infact a better way to print this would be to use format:事实上,更好的打印方式是使用格式:
print "In two year's time you will be: {}".format(int(age) + 2)
age = int(raw_input ('How old are you? '))
print "In two year's time you will be: " , age + 2
age = raw_input ('How old are you? ')
print "In two year's time you will be: " , str(int(age) + 2)
That should work if you are using Python 2.7, not sure if it will work on 3.x如果您使用的是 Python 2.7,那应该可以工作,不确定它是否可以在 3.x 上工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.