【问题标题】:How do I concatenate 'str' and 'int' objects?如何连接“str”和“int”对象?
【发布时间】:2015-10-18 14:57:27
【问题描述】:
age = raw_input ('How old are you? ')
print "In two year's time you will be: " , age + 2

如何让这段代码的最后一行起作用?我在 Python 中运行时收到错误 TypeError: cannot concatenate 'str' and 'int' objects

【问题讨论】:

  • age = int(raw_input('How old are you? ')) ?

标签: python string concatenation


【解决方案1】:

我们可以通过将 age 类型转换为 int 然后将其添加到 int 来连接它。

 age = raw_input ('How old are you? ')
 print "In two year's time you will be: " , int(age) + 2

事实上,更好的打印方式是使用格式:

print "In two year's time you will be: {}".format(int(age) + 2)

【讨论】:

  • 代码有什么问题?请提供对否决票的解释。
【解决方案2】:

使用将int 强制转换为str 并使用str.format 将其添加到您的字符串中:

age = int(raw_input ('How old are you? ')) 
print "In two year's time you will be: {}".format(age + 2)

【讨论】:

  • 这仍然会尝试连接一个字符串和一个 int。
  • 好的,但 str.format 实际上与此错误无关或无关,而您的答案将其作为解决方案。
  • 这是将变量插入字符串的最佳实践方式,优于使用%(请参阅上面链接的文档进行确认)。鉴于操作问题的核心是字符串插值,添加 format() 的使用为他提供了最佳实践知识,以便在他的应用程序变得更加复杂时使用。
  • 推荐使用format也不错,除了说明问题所在。但是将您的答案的整个文本设置为“使用 str.format”意味着不使用它是错误的原因,这是错误的。
【解决方案3】:
age = int(raw_input ('How old are you? '))
print "In two year's time you will be: " , age + 2

【讨论】:

  • @interjay,是的,有些愚蠢......这个想法是你必须先 int() 你的输入。
【解决方案4】:
age = raw_input ('How old are you? ')
print "In two year's time you will be: " , str(int(age) + 2)

如果您使用的是 Python 2.7,这应该可以工作,但不确定它是否可以在 3.x 上工作

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多