I have to use “re” to write a programme that extracts all the numbers of a file and gives the sum of all of them.
I’ve written this:
But it does not work: the mistake is TypeError: expected string or bytes-like object.
Any ideas what I am doing wrong?
Please copy and paste the full error message, starting at the line
“Traceback…” to the end.
Also, please show us the code as text (formatted as code), not a
screenshot or photo.
To debug these sorts of TypeErrors yourself, you should look at the line
which is giving the error:
# Say, you call this line and get TypeError number = re.match(r'\d+', mystring)
and look more closely at “mystring” (which may not actually be a string)
by putting this immediately before the line that fails:
That print line will show you what the variable actually is.
The issue is that hand is a file and *re.findall()*is expecting a string.
One possible fix would be:
hand_file = open('regex_sum.txt') hand_text = hand_file.read() numbers = re.findall('[0-9]+', hand_text) recuento = 0 for text_number in numbers: recuento += int(text_number)