Python类型错误:必须是字符串而不是整数。

26

我有一个问题,关于下面这段代码:

    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周围添加了括号,但仍然出现错误。

3个回答

64

print("现在炉温为" + str(temperature) + "度!")

将其转换为str


谢谢,已解决。 - Eps12 Gaming
please accept the answer :) - PYA
为什么会这样? 为什么不直接调用int的__str__()魔术方法并在嵌入字符串之前转换它? - Danil
@Danil 不是特别确定 - 我得深入研究一下。 - PYA
@Danil,Python通常不会自动强制转换事物(“显式优于隐式”- Python之禅),当使用字符串连接运算符+时,它期望2个字符串,并且如果没有得到2个字符串,则会失败。注意:print()接受多个参数并自动调用这些参数的__str __(),因此您可以执行print(“炉子现在为”,温度,“度!”)而无需显式转换。 - AChampion

18

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!

7

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接