Python无法将float对象隐式转换为str

时间:2018-09-28 01:20:31

标签: python-3.x

我正在尝试编写一个程序,将学校的英里数转换为码英尺和英寸,而我遇到了问题。我使用Flogorithm将代码放在一起,但出现错误“可变脚未初始化”。然后,我将其放入cloud9来测试代码,但出现错误:

itemStyle.normal.textColor = Color.white;

代码是:

line 22, in <module>
    calculateyards (miles)
line 15, in calculateyards
    print("The result is" + yards)
TypeError: Can't convert 'float' object to str implicitly

我真的不擅长函数调用,这就是为什么我遇到这么多问题并且需要帮助的原因。

1 个答案:

答案 0 :(得分:1)

Python是一种强类型语言,因此当串联运算符+期望两个操作数都是字符串时,不会从float到str进行隐式转换。

您应该使用str()构造函数将float变量转换为字符串:

print("The result is " + str(yards))

或使用str.format方法:

print("The result is {}".format(yards))