【问题标题】:What does it mean when it says that it "cannot concatenate 'str' and 'float' objects" on python [duplicate]当它在python上说它“无法连接'str'和'float'对象”时是什么意思[重复]
【发布时间】:2014-05-27 16:38:12
【问题描述】:

我一直在研究 Python 上的毕达哥拉斯定理计算器 到目前为止,这是我的代码:

a = int(raw_input("what is length a?"))
b = int(raw_input("what is length b?"))
a2 = a*a 
b2 = b*b 
c2 = a2+b2
c = c2**0.5
print "the length of c is " + c

它在最后一行不起作用。它抛出以下错误:

cannot concatenate 'str' and 'float' objects

有谁知道它有什么问题吗?

【问题讨论】:

  • 正是错误所说的 - 它不能将字符串(“c 的长度为”)和浮点数(c)放在一起。您需要通过强制转换来告诉它将该数字视为字符串。
  • 下次试试google。当我用谷歌搜索“无法连接 'str' 和 'float' 对象”时,我得到了大约 50 个结果

标签: python


【解决方案1】:

正如它所说:c 是一个浮点数,但 "the length of c is " 是一个字符串。作为一种快速解决方法,您可以这样做:"the length of c is " + str(c),但您需要了解string formatting.

【讨论】:

  • 谢谢,我试过了,效果很好。如果"the length of c is "是字符串,为什么不是str("the length of c is ") + c?
  • 因为"the length of c is "已经是一个字符串,不需要用str()强制转换为字符串类型,这不是问题。问题是c 变量;它不是string 类型,因此不具有字符串固有的类属性(如本例中的串联)。在您的范围内,c 的类型为 int,因此我们必须先将其转换为字符串,然后才能将其视为此类。这样想,c 是一个整数,不能像你不能将它的值设置为大写一样连接起来,谁听说过大写 '45'?
【解决方案2】:

cint"the length of c is " 是字符串

你不得不说

print "the length of c is ", str(c)

【讨论】:

    【解决方案3】:

    试试print "the length of c is %.3f" % (c,)

    串联是将字符串组合在一起,Python 不会自动将非字符串转换为字符串(与 Java 不同)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-13
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      相关资源
      最近更新 更多