Python: TypeError: cannot concatenate #39;str#39; and #39;int#39; 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
与:
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"对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:TypeError:无法连接“str"和“int"对象


- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01