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

运行以下代码后出现错误。


这是代码:


a=input("enter the string value")

b=int(input("enter the number"))

c=a+b

print(c)

这是结果:


enter the string value xyz

enter the number 12

Traceback (most recent call last):

  File "e:/python learning/error1.py", line 3, in <module>      

    c=a+b

TypeError: can only concatenate str (not "int") to str


呼啦一阵风
浏览 265回答 5
5回答

Qyouu

在 Python 中,您不能将字符串添加到 int。为此,您可以使用不同的方法,例如format:a&nbsp;=&nbsp;input("enter&nbsp;the&nbsp;string&nbsp;value") b&nbsp;=&nbsp;int(input("enter&nbsp;the&nbsp;number")) c&nbsp;=&nbsp;"{}{}".format(a,&nbsp;b)该format函数将对象作为参数,并通过str对象的表示来表示它们。在 Python 3.6 及更高版本中,您可以使用that 来执行与在字符串和内部参数之前添加 anf-string相同的操作,例如:formatfc&nbsp;=&nbsp;f'{a}{b}'a这两个选项都将存储和b的串联c。还有另一个选项使用如下print函数:print(a,&nbsp;b,&nbsp;sep="")该print函数接受所有由 a 分隔的参数,并打印str对象的表示 - 就像做的format那样。默认情况下sep,打印选项是将" "在参数之间打印的空格。通过将其更改为""它将按顺序打印参数,中间没有空格。可以在不将另一个变量中的a和的串联存储为 的情况下使用此选项。bc

手掌心

在 python 中,您不能添加具有不同类型(int、float、boolean 等)的字符串值。要获得此代码的结果,您必须以字符串类型或 int 类型更改其中之一。a=input() b=input() c=a+bprint(c)要么&nbsp;a=int(input("enter&nbsp;the&nbsp;number")) &nbsp;&nbsp;&nbsp;&nbsp;b=int(input("enter&nbsp;the&nbsp;number")) &nbsp;&nbsp;&nbsp;&nbsp;c=a+b &nbsp;&nbsp;&nbsp;&nbsp;print(c)

函数式编程

用这个:a=input("enter&nbsp;the&nbsp;string&nbsp;value") b=int(input("enter&nbsp;the&nbsp;number")) c=a+str(b) print(c)输出enter&nbsp;the&nbsp;string&nbsp;valuexyz enter&nbsp;the&nbsp;number12 xyz12

MM们

如果您的最终目标是连接,您实际上不需要将输入转换为 int,只需将其用作输入即可:a=input("enter the string value")b=input("enter the number")c=a+bprint(c)

一只甜甜圈

当你使用+with strings 时,你只能将它与其他字符串连接起来。但是,您试图将它与一个整数连接起来。改为c=a+b_c=a+str(b)str(b)将b整数转换为字符串。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python