Python:TypeError:无法连接“str"和“int"对象

2022-01-14 00:00:00 python string printing integer

问题描述

我有这个将字符串添加到整数的 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

与:

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

相关文章