given string = "12ab23cdef456gh789"
, sum the number, output should be 12 23 456 789 = 1280
my code:
s = "ab12cd23ed456gh789"
st = ''
for letter in s:
if letter.isdigit():
st = letter
else:
if st[-1].isdigit():
st = ','
st = [int(letter) for letter in st.split(',')]
print(st)
print(sum(st))
error:
Traceback (most recent call last):
if st[-1].isdigit():
IndexError: string index out of range
Process finished with exit code 1
not sure where i am going wrong, can someone please help me here?
CodePudding user response:
You can use a regular expression to extract all consecutive sequences of digits.
import re
string = "12ab23cdef456gh789"
res = sum(map(int, re.findall(r'\d ', string)))
print(res)
CodePudding user response:
The issue with your code is that for the first letter, st
is empty and you're trying to get the last element, which does not exist. Just add a check to make sure st
isn't empty like this:
s = "ab12cd23ed456gh789"
st = ''
for letter in s:
if letter.isdigit():
st = letter
else:
if len(st) != 0 and st[-1].isdigit():
st = ','
st = [int(letter) for letter in st.split(',')]
print(st)
print(sum(st))
However, it is generally better to use a regular expression for this instead. I know this is probably a homework question so you can't use a regular expression, but here's how you'd do one anyway:
import re
s = "ab12cd23ed456gh789"
n = sum([int(match) for match in re.findall(r'\d ', s)])
print(n)