【问题标题】:can only concatenate str (not 'int') to str [duplicate]只能将str(不是'int')连接到str [重复]
【发布时间】:2018-12-26 16:26:25
【问题描述】:

我想做一个简单的加法程序,但遇到如下错误: TypeError: 只能将str(不是'int')连接到str。

我不知道该怎么做,我对 Python 编码还很陌生。

def addition():
    x = int(input("Please enter the first number:"))
    y = int(input("Please enter the second number:"))
    z = x+y
    print("The sum of " +x+ " and " +y+ " gives " +z )

我希望代码返回两个输入值之和的值。

【问题讨论】:

  • 推荐你看official Python tutorial,挺好的。
  • 非常感谢所有帮助过的人,我知道这是一个愚蠢的问题,但我仍然是 Python 编码的新手。再次感谢...

标签: python


【解决方案1】:

+ 运算符可以在多个上下文中工作。在这种情况下,相关的用例是:

  • 连接内容时(例如strings);

  • 当您想要添加数字时(intfloat 等)。

因此,当您在同时使用字符串和 int 变量(xyz)的概念中使用 + 时,Python 将无法正确处理您的意图。在您的情况下,您希望将句子中的数字连接起来,就好像它们是单词一样,您必须将您的数字从 int 格式转换为 string 格式。在这里,见下文:

def addition():
    x = int(input("Please enter the first number:"))
    y = int(input("Please enter the second number:"))
    z = x+y
    print("The sum of " + str(x) + " and " + str(y) + " gives " + str(z))

【讨论】:

  • "只能处理字符串"。真的吗?列表呢?
  • 糟糕,我的错!已改进,谢谢提醒!
  • 欣赏编辑,但我认为你太仓促了 :) 现在你说+ 不适用于数字。事实上,符号将根据类型进行不同的解释。
  • 在使用字符串的上下文中,+ 将用作连接运算符。但我明白你的意思。请稍等一下,让我更好地说明 Python 为何会发生冲突。
  • 好的,已修复。非常感谢您的建议和耐心:)
【解决方案2】:

问题是当您打印输出 (print("The sum of " +x+ " and " +y+ " gives " +z )) 时,您正在将字符串添加到整数(xyz)。

尝试替换为

print("The sum of {0} and {1} gives {2}".format(x, y, z))

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2021-02-15
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2021-11-07
    • 2020-09-18
    相关资源
    最近更新 更多