程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Python:TypeError:无法连接'str'和'int'对象[重复]

发布于2019-08-22 09:14     阅读(1011)     评论(0)     点赞(19)     收藏(1)


这个问题在这里已有答案:

我有这个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

如何将字符串添加到整数?


解决方案


有两种方法可以解决由最后一个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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/51715/827d6a99eba416725c51/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)