Skip to content
Advertisement

Python27 TypeError: unsupported operand for type(s) += ‘int’ and ‘str’

Please help me understand what’s happening here. My aim is to create a function that will read “input.txt” and return the min, max, and average for each line within the text document. The text within the document is as follows:

JavaScript

My code looks like this:

JavaScript

Everything prints out fine except for numSum, which gives the error mentioned in the heading.

Advertisement

Answer

re.findall gives you back a list of strings, something like ["foo", "bar", "baz"]. The implementation of sum is something like this:

JavaScript

So at some point, it’ll attempt to execute a line like total = 0 + "foo" and fall over, since Python doesn’t know how to add an int to a string. The fact that you know all your strings actually contain ints is immaterial, since the expression 1+'1' might sensibly evaluate to either '11' or 2, and Python won’t guess which.

As you read in each line, you should convert every string to an int. That ought to solve your problem

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement