Python TypeError必须是str而不是int

时间:2017-07-05 03:39:47

标签: python python-3.x typeerror

我在使用以下代码时遇到问题:

    if verb == "stoke":

        if items["furnace"] >= 1:
            print("going to stoke the furnace")

            if items["coal"] >= 1:
                print("successful!")
                temperature += 250 
                print("the furnace is now " + (temperature) + "degrees!")
                           ^this line is where the issue is occuring
            else:
                print("you can't")

        else:
            print("you have nothing to stoke")

产生的错误如下:

    Traceback(most recent call last):
       File "C:\Users\User\Documents\Python\smelting game 0.3.1 build 
       incomplete.py"
     , line 227, in <module>
         print("the furnace is now " + (temperature) + "degrees!")
    TypeError: must be str, not int

我不确定问题是什么,因为我已将名称从温度更改为温度并在温度附近添加了括号但仍然出现错误。

3 个答案:

答案 0 :(得分:32)

print("the furnace is now " + str(temperature) + "degrees!")

将其投放到str

答案 1 :(得分:12)

Python提供了多种格式化字符串的方法:

新样式.format(),支持丰富的格式化迷你语言:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

旧样式%格式说明符:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

在Py 3.6中使用新的f""格式字符串:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

或使用print()默认sep人:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

最不实际的是,通过将其转换为str()并连接来构造一个新字符串:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

join()

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

答案 2 :(得分:2)

你需要在连接之前将int转换为str。使用str(temperature)。或者,如果您不想像这样转换,可以使用,打印相同的输出。

print("the furnace is now",temperature , "degrees!")