【问题标题】:"Can't convert 'float' object to str implicitly" [duplicate]“无法将'float'对象隐式转换为str”[重复]
【发布时间】:2014-04-19 06:53:59
【问题描述】:
>>> def main():
        fahrenheit = eval(input("Enter the value for F: "))
        celsius = fahrenheit - 32 * 5/9
        print("The value from Fahrenheit to Celsius is " + celsius)
>>> main()
Enter the value for F: 32
Traceback (most recent call last):  
  File "<pyshell#73>", line 1, in <module>
    main()
  File "<pyshell#72>", line 4, in main
    print("The value from Fahrenheit to Celsius is " + celsius)
TypeError: Can't convert 'float' object to str implicitly"

【问题讨论】:

    标签: python typeerror


    【解决方案1】:

    floats 不能隐式转换为字符串。你需要明确地这样做。

    print("The value from Fahrenheit to Celsius is " + str(celsius))
    

    但最好使用format

    print("The value from Fahrenheit to Celsius is {0}".format(celsius))
    

    【讨论】:

    • 如果您使用的是 Python 2.7+,您可以省略 str.format 中的位置参数说明符,因此 {0} 等同于 {}
    • “但是最好使用format。”你能解释一下为什么吗?
    【解决方案2】:

    正如错误所说,您不能将浮点对象隐式转换为字符串。你必须这样做:

    print("The value from Fahrenheit to Celsius is " + str(celsius))
    

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 2018-12-26
      • 2017-08-31
      相关资源
      最近更新 更多