Home > Enterprise >  How to remove the error of 'can only concatenate str (not "float") to str' in Py
How to remove the error of 'can only concatenate str (not "float") to str' in Py

Time:12-01

I am trying to calculate a percentage of landmass occupied by a country from the total landmass.I am taking two arguments as string and float in a function and returning String along with the calculated percentage in it. For example the Input =area_of_country("Russia", 17098242) and Output = "Russia is 11.48% of the total world's landmass". Below is my code

    class Solution(object):

    def landmass(self, st, num):
        percentage = 148940000 / num * 100

        return st   "is"   percentage   "of total world mass!"


if __name__ == "__main__":

    s = "Russia"
    n = 17098242
    print(Solution().landmass(s, n))

Error :-

        return st   "is"   percentage   "of total world mass!"
TypeError: can only concatenate str (not "float") to str

CodePudding user response:

You need to cast the percentage (since it's a float) into a string when concatenating using the operator. So your return statement would look like:

return str(st)   "is"   str(percentage)   "of total world mass!"

CodePudding user response:

instead of this:

return st "is" percentage "of total world mass!"

Try this:

return str(st)   "is"   str(percentage)   "of total world mass!"
  • Related