Sum of all digits in a string Given a string, return the sum of all the numbers in the string, 0 if none are present.


Below is my solution for the problem above. I feel like this can be turned into one line. I would really only like suggestions on the actual algorithm, but anything else is appreciated.

def sum_numbers(string: str) -&gt; int:
    """
    Returns the sum of all the numbers in the string
    """
    num_sum = 0
    for char in string:
        if char.isnumeric():
            num_sum += int(char)
    return num_sum

if __name__ == '__main__':

    # Test Cases #

    assert sum_numbers("123") == 6
    assert sum_numbers("abc") == 0
    assert sum_numbers("4x7") == 11
    assert sum_numbers("wefbyug87iqu") == 15
    assert sum_numbers("123456789") == 45
You're right, it can be turned into one line using comprehension syntax which would be your best option of you're looking for a slightly more efficient code.


isdecimal() is better to use in this case than isnumeric() because the isnumeric() accepts types like ½ and ¼ and n² which might produce some side effects you don't want if you're using this function for some real application. Apart from this the code looks good, can be improved using the comprehension syntax which is more efficient and shorter.


Improved version:

def sum_digits(chars: str) -&gt; int:
    """Return sum of numbers in chars"""
    return sum(int(char) for char in chars if char.isdecimal())


if __name__ == '__main__':
    print(sum_digits('abcd173fg'))
    print(sum_digits('abcd'))
    print(sum_digits('173678'))