首页 > 解决方案 > TypeError:只能将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

标签: python

解决方案


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

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

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

在 Python 3.6 及更高版本中,您可以使用f-stringthat 将执行相同的操作,方法是在字符串之前format添加一个并在内部添加参数,例如:f

c = f'{a}{b}'

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


print使用该功能还有另一个选项,例如:

print(a, b, sep="")

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

可以使用此选项,而无需将 和 的串联存储ab另一个变量中作为c.


推荐阅读