【问题标题】:Why do I get "TypeError: cannot concatenate 'str' and 'int' objects"? [duplicate]为什么我会收到“TypeError:无法连接 'str' 和 'int' 对象”? [复制]
【发布时间】:2019-02-13 00:24:08
【问题描述】:

当我在行中输入我的变量时,我得到了 TypeError。

num = int(input("Enter a number"))
print("You are " + num * 7 + " dog years old")

我希望它只接受输入,然后将其乘以 7 并给出最终数字,但我只是得到了错误。我几乎不了解 str 和 int,因此对它们的解释也会有所帮助。

【问题讨论】:

  • 您不能连接字符串和整数。请参阅字符串的文档。 docs.python.org/3/library/stdtypes.html#str我想你正在寻找类似的东西:print("You are " + str(num * 7) + " dog years old")
  • 如果你使用的是最近的python,你可以做 print(f"You are {num*7} dog years old")

标签: python python-3.x string exception input


【解决方案1】:

将数字转换为字符串:

num = int(input("Enter a number."))
print ("You are " + str(num * 7) + " dog years old")

由于错误状态,您不能连接字符串和整数:

TypeError: 不能连接 'str' 和 'int' 对象?

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 2015-09-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多