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

885 阅读1分钟

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

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

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

result = 'Orange price is ' + 9.99
print (result)

输出。

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    result = 'orange price is ' + 9.99
TypeError: can only concatenate str (not "float") to str

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

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

str() 函数将浮动值作为一个参数,并将其转换为字符串。

下面是一个例子。

result = 'Orange price is ' + str(9.99)
print (result)

输出。

'Orange price is 9.99'

我们还可以使用Python中的type() 函数来检查一个变量持有的数据类型。

price = 9.99  # integer
print(type(price)) # <class 'int'>

orange_txt = 'Orange price is '
print(type(orange_txt)) # <class 'str'>

type() 函数返回一个变量持有的数据的类型。

结论

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