为了账号安全,请及时绑定邮箱和手机立即绑定

类型错误:只能将 str(不是“int”)连接到 str123

类型错误:只能将 str(不是“int”)连接到 str123

呼啦一阵风 2023-01-04 11:21:27
运行以下代码后出现错误。这是代码:a=input("enter the string value")b=int(input("enter the number"))c=a+bprint(c)这是结果:enter the string value xyzenter the number 12Traceback (most recent call last):  File "e:/python learning/error1.py", line 3, in <module>          c=a+bTypeError: can only concatenate str (not "int") to str
查看完整描述

5 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

在 Python 中,您不能将字符串添加到 int。为此,您可以使用不同的方法,例如format

a = input("enter the string value")
b = int(input("enter the number"))
c = "{}{}".format(a, b)

format函数将对象作为参数,并通过str对象的表示来表示它们。

在 Python 3.6 及更高版本中,您可以使用that 来执行与在字符串和内部参数之前添加 anf-string相同的操作,例如:formatf

c = f'{a}{b}'

a这两个选项都将存储和b的串联c


还有另一个选项使用如下print函数:

print(a, b, sep="")

print函数接受所有由 a 分隔的参数,并打印str对象的表示 - 就像做的format那样。默认情况下sep,打印选项是将" "在参数之间打印的空格。通过将其更改为""它将按顺序打印参数,中间没有空格。

可以在不将另一个变量中的a和的串联存储为 的情况下使用此选项。bc


查看完整回答
反对 回复 2023-01-04
?
手掌心

TA贡献1942条经验 获得超3个赞

在 python 中,您不能添加具有不同类型(int、float、boolean 等)的字符串值。要获得此代码的结果,您必须以字符串类型或 int 类型更改其中之一。

a=input()
b=input()
c=a+bprint(c)

要么

 a=int(input("enter the number"))
    b=int(input("enter the number"))
    c=a+b
    print(c)


查看完整回答
反对 回复 2023-01-04
?
函数式编程

TA贡献1807条经验 获得超9个赞

用这个:

a=input("enter the string value")
b=int(input("enter the number"))
c=a+str(b)
print(c)

输出

enter the string valuexyz
enter the number12
xyz12


查看完整回答
反对 回复 2023-01-04
?
MM们

TA贡献1886条经验 获得超2个赞

如果您的最终目标是连接,您实际上不需要将输入转换为 int,只需将其用作输入即可:


a=input("enter the string value")

b=input("enter the number")

c=a+b

print(c)


查看完整回答
反对 回复 2023-01-04
?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

当你使用+with strings 时,你只能将它与其他字符串连接起来。但是,您试图将它与一个整数连接起来。

改为c=a+b_c=a+str(b)

str(b)b整数转换为字符串。


查看完整回答
反对 回复 2023-01-04
  • 5 回答
  • 0 关注
  • 264 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号