Program to find sum of digits that are inside one alphanumeric string in Python

Suppose we have an alphanumeric string with digits from "0" to "9" and lowercase English letters. We need to find the sum of all numbers present in the string. If digits are consecutive, they form a single number.

For example, if the input is s = "hello25world63power86", the output will be 174 because 25 + 63 + 86 = 174.

Algorithm

To solve this problem, we follow these steps −

  • Initialize ret = 0 (final sum) and curr = 0 (current number being built)

  • For each character in the string:

    • If character is a digit, build the current number: curr = 10 * curr + digit

    • If character is not a digit, add current number to result and reset: ret += curr, curr = 0

  • Return ret + curr (add the last number if string ends with digits)

Example

Let us see the implementation to get better understanding −

def solve(s):
    ret = 0
    curr = 0
    for ch in s:
        if ch.isdigit():
            curr = 10 * curr + int(ch)
        else:
            ret += curr
            curr = 0
    return ret + curr

s = "hello25world63power86"
print(solve(s))
174

How It Works

For the string "hello25world63power86"

  • h,e,l,l,o: Not digits, curr remains 0

  • 2,5: Digits, curr = 0*10+2 = 2, then curr = 2*10+5 = 25

  • w: Not digit, ret = 0 + 25 = 25, curr = 0

  • 6,3: Digits, curr = 63

  • p: Not digit, ret = 25 + 63 = 88, curr = 0

  • 8,6: Digits, curr = 86

  • End of string: ret = 88 + 86 = 174

Alternative Approach Using Regular Expressions

import re

def solve_regex(s):
    numbers = re.findall(r'\d+', s)
    return sum(int(num) for num in numbers)

s = "hello25world63power86"
print(solve_regex(s))
174

Conclusion

Use the iterative approach for better understanding of the algorithm. The regex approach is more concise but requires importing the re module. Both methods efficiently extract and sum consecutive digits from alphanumeric strings.

Updated on: 2026-03-26T15:08:57+05:30

663 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements