Python TypeError必须是str而不是int

Eps*_*ing 11 python typeerror python-3.x

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

    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")
Run Code Online (Sandbox Code Playgroud)

产生的错误如下:

    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
Run Code Online (Sandbox Code Playgroud)

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

PYA*_*PYA 40

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

把它投到 str


ACh*_*ion 12

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

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

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
Run Code Online (Sandbox Code Playgroud)

旧样式%格式说明符:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
Run Code Online (Sandbox Code Playgroud)

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

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
Run Code Online (Sandbox Code Playgroud)

或者使用print()s默认的separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
Run Code Online (Sandbox Code Playgroud)

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

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
Run Code Online (Sandbox Code Playgroud)

或者join()说:

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


bad*_*iya 5

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

print("the furnace is now",temperature , "degrees!")
Run Code Online (Sandbox Code Playgroud)