Python TypeError 必须是 str 而不是 int

Python TypeError must be str not int

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

    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

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

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

投射到str

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

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

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() 的默认值 separator:

>>> 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!