Sum of digits in a string

前端 未结 8 2030
天涯浪人
天涯浪人 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:31

    You're resetting the value of b on each iteration, if a is a digit.

    Perhaps you want:

    b += int(a)
    

    Instead of:

    b = int(a)
    b += 1
    
    0 讨论(0)
  • 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)))
    
    0 讨论(0)
提交回复
热议问题