TypeError: unsupported operand type(s) for +: 'int' and 'str' when using str(sum(list))

血红的双手。 提交于 2021-02-17 05:24:42

问题


I'm going through the Python tutorial and have no idea why my code isn't working. I know I need to tell Python to print an integer manually but I have already put str(sum(ages)). Can anyone tell me why this is happening?

ages = ['24','34','51','36','57','21','28']

print('The oldest in the group is ' + str(max(ages)) + '.')

print('The youngest in the group is ' + str(min(ages)) + '.')

print('The combined age of all in the list is ' + str(sum(ages)) + '.')

Error:

File "list2.py", line 4, in <module>
    print('The combined age of all in the list is ' + str(sum(ages)) + '.')

TypeError: unsupported operand type(s) for +: 'int' and 'str'

回答1:


The issue is that you can't use sum on a list of strings. In order to do this, you can use a generator expression to convert each element to an integer first:

print('The combined age of all in the list is ' + str(sum(int(x) for x in ages)) + '.')

Which gives us:

The combined age of all in the list is 251.


来源:https://stackoverflow.com/questions/59965010/typeerror-unsupported-operand-types-for-int-and-str-when-using-strsum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!