我有一个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
如何将字符串添加到整数中?
发布于 2012-08-07 18:38:04
有两种方法可以修复由最后一条print
语句引起的问题。
您可以将@jamylak正确显示的str(c)
调用的结果赋值给c
,然后连接所有字符串,也可以简单地将最后一个print
替换为:
print "a + b as integers: ", c # note the comma here
在这种情况下
str(c)
不是必需的,可以删除。
示例运行的输出:
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
发布于 2012-08-07 18:37:35
如果您想将int或float连接到一个字符串,则必须使用以下命令:
i = 123
a = "foobar"
s = a + str(i)
发布于 2013-10-25 17:38:28
c = a + b
str(c)
实际上,在这最后一行中,您并没有更改变量c的类型。
c_str=str(c)
print "a + b as integers: " + c_str
应该能行得通。
https://stackoverflow.com/questions/11844072
复制相似问题