简体   繁体   中英

sum of num in given string

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM