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

PythonServer Side ProgrammingProgramming

Suppose we have an alphanumeric string s with digits from "0" to "9" and lowercase English letters. We have to find the sum of the numbers that are present in s. If digits are consecutive then consider them into a single number.

So, if the input is like s = "hello25world63power86", then the output will be 174 because 25+63+86 = 174

To solve this, we will follow these steps −

• ret := 0, curr := 0

• for each ch in s, do

• if ch is a digit, then

• curr := 10 * curr + (ch as an integer)

• otherwise,

• ret := ret + curr

• curr := 0

• return ret + curr

## Example

Let us see the following implementation to get better understanding

from string import digits
def solve(s):
ret = 0
curr = 0
for ch in s:
if ch in digits:
curr = 10 * curr + int(ch)
else:
ret += curr
curr = 0
return ret + curr

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

## Input

"hello25world63power86"


## Output

174
Updated on 11-Oct-2021 06:40:39