Sum of digits in a string

前端 未结 8 2054
天涯浪人
天涯浪人 2020-12-06 12:35

if i just read my sum_digits function here, it makes sense in my head but it seems to be producing wrong results. Any tip?

def is_a_digit(s):
\         


        
8条回答
  •  不知归路
    2020-12-06 13:35

    I would like to propose a different solution using regx that covers two scenarios:

    1.
    Input = 'abcd45def05'
    Output = 45 + 05 = 50

    import re
    print(sum(int(x) for x in re.findall(r'[0-9]+', my_str)))
    

    Notice the '+' for one or more occurrences

    2.
    Input = 'abcd45def05'
    Output = 4 + 5 + 0 + 5 = 14

    import re
    print(sum(int(x) for x in re.findall(r'[0-9]', my_str)))
    

提交回复
热议问题