如何去除'的错误;只能将str(不是"float")连接到str'在Python中返回



我正试图计算一个国家占总陆地面积的百分比。我在一个函数中取两个参数作为字符串和浮点数,并返回字符串以及其中计算的百分比。例如Input =area_of_country("Russia", 17098242)产出= "俄罗斯占世界陆地总面积的11.48% ">. 下面是我的代码

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))

错误:-

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

在使用+操作符进行连接时,需要将百分比(因为它是浮点数)转换为字符串。所以你的返回语句看起来像:

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

而不是:

return st + "is"+占世界总质量的百分比">

试试这个:

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

最新更新