【问题标题】:Python TypeError must be str not int [duplicate]Python TypeError 必须是 str 而不是 int [重复]
【发布时间】:2017-12-08 13:20:57
【问题描述】:

以下代码有问题:

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

【问题讨论】:

    标签: python python-3.6 typeerror


    【解决方案1】:

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

    投给str

    【讨论】:

    • 谢谢,成功了
    • 请接受答案:)
    • 为什么会这样?为什么不直接调用 int 的 __str__() 魔法方法,在嵌入到字符串之前进行转换?
    • @Danil 不太确定——我得深入研究一下
    • @Danil python 通常不会自动强制执行某些事情(“显式优于隐式”- Python 之禅),当使用字符串的连接运算符 + 时,它需要 2 个字符串,如果没有,则会失败没有得到 2 个字符串。注意:print() 接受多个参数并在这些参数上自动调用 __str__(),这就是为什么你可以这样做,print("the furnace is now ", temperature, "degrees!") 无需显式转换。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      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()s 默认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()ing它:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 2020-11-22
        • 2018-07-23
        • 2018-04-26
        • 1970-01-01
        相关资源
        最近更新 更多