Python:TypeError:无法连接“ str”和“ int”对象
我有这个将字符串添加到整数的python程序:
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
如何将字符串添加到整数?
回答:
有两种方法可以解决由最后一条print语句引起的问题。
你可以将str(c)
调用的结果分配给c@jamylak
正确显示的结果,然后连接所有字符串,或者可以使用以下内容替换最后一个字符串print:
print "a + b as integers: ", c # note the comma here
在这种情况下
str(c)
不必要,可以删除。
样品运行的输出:
Enter a: 3Enter b: 7
a + b as strings: 37
a + b as integers: 10
与:
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”对象 的全部内容, 来源链接: utcz.com/qa/428637.html