Python:TypeError:无法连接'str'和'int'对象 [英] Python: TypeError: cannot concatenate 'str' and 'int' objects
本文介绍了Python:TypeError:无法连接'str'和'int'对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个为整数添加字符串的python程序:
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
我收到此错误:
Python: TypeError: cannot concatenate 'str' and 'int' objects
如何将字符串添加到整数?
How can I add strings to integers?
推荐答案
有两种方法可以解决由上一个 print
语句引起的问题。
There are two ways to fix the problem which is caused by the last print
statement.
您可以将 str(c)
的结果分配给 c
正如@jamylak正确显示然后连接所有字符串,或者您可以使用以下内容替换最后的 print
:
You can assign the result of the str(c)
call to c
as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print
simply with this:
print "a + b as integers: ", c # note the comma here
在这种情况下
str(c)
不是必需的,可以删除。
isn't necessary and can be deleted.
样本运行的输出:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
这篇关于Python:TypeError:无法连接'str'和'int'对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文