TypeError:无法连接'str'和'float'对象python 2.7

时间:2018-01-25 17:30:08

标签: python-2.7

我正在尝试编写一个成功将华氏温度转换为摄氏温度的代码,但我一直收到一条错误,指出“TypeError:无法连接'str'和'float'对象”

以下代码:

a = float(raw_input("What is the temperature in fahrenheit ")) 
b = (a-32)/1.8 
c = "Your temperature is " + b + " degrees celsius."

2 个答案:

答案 0 :(得分:1)

当Python看到string + float + string时,它不知道该怎么做(大多数其他语言都没有)。

为了获得您正在寻找的结果,您需要先将b转换为字符串。 有几种方法可以执行此操作,具体取决于转换后要为b保留的小数位数。

这是一个有用的堆栈溢出问题,应该可以帮助您:)

Converting a float to a string without rounding it

答案 1 :(得分:0)

您需要将b从float更改为string:

c = "Your temperature is " + str(b) + " degrees celsius."

或者,您可以使用替换来打印输出:

c = "Your temperature is %s degrees celsius." % b