解决TypeError: can only concatenate str (not "int") to str的问题

1,243 阅读1分钟

在本教程中,我们将学习如何在Python中解决TypeError: can only concatenate str (not "int") to str的问题。

当我们试图将一个字符串连接到一个整数时,我们会得到TypeError:只能将str(不是 "int")连接到str,因为在Python中,只有当两个值都属于同一数据类型时,我们才会进行连接。

下面是一个错误发生的例子。

name = 'John' # string
id = 11    # integer

result = name + id
print (result)

输出。

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    print (name + id)
TypeError: can only concatenate str (not "int") to str

在上面的例子中,我们使用+ 加运算符来连接字符串和整数,但是这两个值是不同的数据类型,所以在终端出现了错误。

为了解决这个错误,使用str() 函数将整数值转换为字符串,然后使用+ 操作符将其连接起来。

下面是一个例子。

name = 'John' # string
id = 11    # integer

result = name + str(id)
print (result)

输出。

'John11'

结论

当我们试图连接字符串和整数时,出现了 "只能将str(而不是int)连接到str "的错误。为了解决这个错误,使用str() 函数将整数转换成字符串,然后将其添加到字符串中。