TypeError: cannot concatenate 'str' and 'float' objects - MCEdit

341 views Asked by At

I have this:

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

It gives me the error shown in the title, help please!

3

There are 3 answers

0
Steinar Lima On BEST ANSWER

Another (and much better way) of doing this is to use the str.format method:

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

You can also specify the precision using format:

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

You are getting this error because you are trying to concatenate a string with floats. Python, being a strongly typed language will not allow that. Therefore, you have to convert the rotx and roty values to strings as follows:

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

If you want your values (rotx and roty) to have a certain precision in decimal points, you can do:

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

>>> rotx = 1234.35479334
>>> str(round(rotx, 5))
'1234.35479'
0
Sharif Mamun On

Simply try this:

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