【问题标题】:TypeError: cannot concatenate 'str' and 'float' objects - MCEditTypeError:无法连接 'str' 和 'float' 对象 - MCEdit
【发布时间】:2014-03-27 00:57:29
【问题描述】:

我有这个:

    rotValues = '[rx='+ rotx + ',' + "ry=" + roty +"]" 

它给了我标题中显示的错误,请帮助!

【问题讨论】:

  • 你应该看看字符串插值或字符串格式化。两者都可以轻松打印具有一定精度的浮点数

标签: python typeerror mcedit


【解决方案1】:

另一种(更好的方法)是使用str.format 方法:

>>> rotx, roty = 5.12, 6.76
>>> print '[rx={},ry={}]'.format(rotx, roty)
[rx=5.12,ry=6.76]

您还可以使用format 指定精度:

>>> print '[rx={0:.1f},ry={1:.2f}]'.format(rotx, roty)
[rx=5.1,ry=6.76]

【讨论】:

    【解决方案2】:

    试试这个:

    >>> rotValues = '[rx='+ str(rotx) + ',' + "ry=" + str(roty) +"]" 
    >>> print rotValues
    [rx=1.0,ry=2.0]
    

    【讨论】:

      【解决方案3】:

      您收到此错误是因为您尝试将字符串与浮点数连接。 Python 作为一种强类型语言是不允许的。因此,您必须将rotxroty 值转换为字符串,如下所示:

      rotValues = '[rx='+ str(rotx) + ',' + "ry=" + str(roty) +"]"

      如果您希望您的值(rotxroty)具有一定的小数点精度,您可以这样做:

      rotValues = '[rx='+ str(round(rotx,3)) + ',' + "ry=" + str(round(roty,3)) +"]"

      >>> rotx = 1234.35479334
      >>> str(round(rotx, 5))
      '1234.35479'
      

      【讨论】:

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