gpt4 book ai didi

python - 类型错误 : cannot concatenate 'str' and 'int' objects

转载 作者:IT老高 更新时间:2023-10-28 12:29:37 35 4
gpt4 key购买 nike

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

我收到此错误:

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: 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

关于python - 类型错误 : cannot concatenate 'str' and 'int' objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11844072/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com