Reputation: 1
So I've been reading through "Python for Everybody" and was trying to complete chapter 11 exercise 2 when my code didn't work.
fhand = open("mboxshort.txt")
summation = list()
count = 0
import re
for line in fhand:
line = line.rstrip()
x = re.findall("^New Revision:\s([0-9]+)", line)
if len(x) > 0:
x = float(x)
summation.append(x)
count += 1
print(sum(summation)/count)
The error that comes up is: TypeError: float() argument must be a string or a real number, not 'list'. My question is why does it count x as a list when it's a string to begin with, and how do I fix this error?
Upvotes: 0
Views: 32
Reputation: 413
Check re.findall() documentation, you will see that it returns a list
!
Taking a look into its source code:
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
That's why you can't cast x
to float
!
In doubt, you can check its type:
print(type(x))
<class 'list'>
Upvotes: 1