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"对象
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
