1

I'm attempting to run the following bit of code in python.

import re
text = 'Hello 16 Hello 22 Hello 81 Hello 50'
sum = 0
for m in re.finditer('Hello', text):
  print('found', m.start(), m.end())
  a = m.end()
  b = m.end()+3
  print (text[a:b])
  block = str(text[a:b])
  sum += block
  print (sum)

I am continually getting this error:

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

All I want to do is have my code parse through the text and add together specified numbers contained in it.

Does anyone know what I'm doing wrong?

Thanks

3
  • you need to cast the matched block into an int before summing. Commented Aug 15, 2015 at 14:51
  • Replace with sum = sum +int( block) Commented Aug 15, 2015 at 14:52
  • 1
    @user1929959 how will that help?! Augmented assignment is (generally) the same as the standard equivalent; sum = sum + block will have exactly the same error as sum += block. Commented Aug 15, 2015 at 14:52

3 Answers 3

2

You can't add an str to an int in sum += block. You should convert block first to int. Change line:

 block = str(text[a:b])

to:

 block = int(text[a:b])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Changing to int fixed it.
0

Your sum is an int and you are trying to add a str to it. I think you mean

  block = int(text[a:b])

Comments

0

Maybe I've understood something wrong but to find some numbers in a string you can just use r'\d+'. This code will sum all numbers in a string:

sum(int(i) for i  in re.findall(r'\d+', 'Hello, 7, 89 Vlad'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.