【问题标题】:Why do I get the "TypeError: must be str, not float" error. I tried to convert it [duplicate]为什么我会收到“TypeError:必须是 str,而不是 float”错误。我试图转换它[重复]
【发布时间】:2019-03-15 11:59:39
【问题描述】:

这是我现在要使用的代码。当我运行它时,一切都很好,接受所有温度时它不会打印任何东西,但会给我错误,“TypeError:必须是 str,而不是 float”。

    #temperature, kian, Thursday/March/14, working with variables. 
#this code is going to ask for a temperature in celsius then it will turn celsius temperature into fahrenheit.
celsius = float(input('what is the temperature in celsius? '))
((9.0 / 5.0) * celsius + 32.0)

#this code will ask for a temperature in fahrenheit and then will convert it into celsius.
fahrenheit = float(input('Enter a temperature in Fahrenheit. '))
(5.0 * (fahrenheit - 32.0)) / 9.0

#these prints should print out what was converted but there is an error of needing it to be a str not a float.
print ('the fahrenheit from celsius is, ' + celsius)
print ('the celsius from fahrenheit is, ' + fahrenheit)

提前感谢大家的帮助。

【问题讨论】:

  • 打印时需要将celsiusfahrenheit 转换成字符串
  • ((9.0 / 5.0) * celsius + 32.0) 这个statemebnt没有效果...

标签: python


【解决方案1】:
print ('the fahrenheit from celsius is, ' + str(celsius))
print ('the celsius from fahrenheit is, ' + str(fahrenheit))

这将解决我们将字符串连接在一起的问题。

我们也可以通过以下方式进行格式化:

print ('the fahrenheit from celsius is %.2f ' % celsius)
print ('the celsius from fahrenheit is %.3f ' % fahrenheit)

分别打印出 2 位或 3 位小数。

【讨论】:

  • 使用字符串格式会更好...
  • 如何删除这个问题。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2019-04-23
  • 2018-04-26
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多