close

[Solved] Cannot concatenate ‘str’ and ‘float’ objects?

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Cannot concatenate ‘str’ and ‘float’ objects? in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Cannot concatenate ‘str’ and ‘float’ objects Error Occurs?

Today I get the following error Cannot concatenate ‘str’ and ‘float’ objects? in python.

How To Solve Cannot concatenate ‘str’ and ‘float’ objects Error ?

  1. How To Solve Cannot concatenate 'str' and 'float' objects Error ?

    To Solve Cannot concatenate 'str' and 'float' objects Error All floats or non string data types must be casted to strings before concatenation

  2. Cannot concatenate 'str' and 'float' objects?

    To Solve Cannot concatenate 'str' and 'float' objects Error All floats or non string data types must be casted to strings before concatenation

Solution 1

All floats or non string data types must be casted to strings before concatenation

This should work correctly: (notice the str cast for multiplication result)

easygui.msgbox=("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")

straight from the interpreter:

>>> radius = 10
>>> height = 10
>>> msg = ("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
>>> print msg
You need 3140.0gallons of water to fill this pool.

Solution 2

There is one more solution, You can use string formatting (similar to c language I guess)

This way you can control the precision as well.

radius = 24
height = 15

msg = "You need %f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)

msg = "You need %8.2f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)

without precision

You need 27129.600000 gallons of water to fill this pool.

With precision 8.2

You need 27129.60 gallons of water to fill this pool.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read