TypeError:无法连接“str”和“float”对象MCEdi

2024-06-08 08:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个:

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

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


Tags: 标题错误rxryrotxrotyrotvalues
3条回答

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

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

也可以使用format指定精度:

^{pr2}$

您得到这个错误是因为您正在尝试将一个字符串与浮点数连接起来。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'

只要试试这个:

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

相关问题 更多 >