Hello Everyone, in this tutorial we are going to write a simple program in python to calculate the sum of all numbers and digits in an alpha-numeric string.

Recently, I attend an interview on our campus. In the interview, the interviewer asked me to solve this problem.
This is a very simple problem, just the basics of a language are enough for one to solve this problem.
Algorithm to solve the problem:
1. Take the string input from the user and store it in variable n
.
2. Initialize sum = 0, temp_num = 0
3. Now loop through all characters in that string.
4. If it is an alphabet, ignore it
5. If it is a numeric value, append it to variable temp_num
until the next character is an alphabet and add temp_num
to the sum.
6. Finally, print the sum at the end of the program. Thus gives the sum of all numbers in an alpha-numeric string.
1. Code for Sum of all Numbers in Alpha-Numeric String
Let's see how we can find the sum of numbers in alpha numeric string. So for example the string is s1s22s33, then numbers are 1, 22 and 33.
#1. Without Recursion
n = input("Enter an Alpha-Numeric String: ")
n_sum = 0
temp_num = ""
for i in n:
if( i.isalpha() ):
if( temp_num != "" ):
n_sum = n_sum + int(temp_num)
temp_num = 0
else:
temp_num = str(temp_num) + str(i)
if( temp_num != "" ):
n_sum = n_sum + int(temp_num)
temp_num = 0
print(n_sum)
Enter an Alpha-Numeric String: s1s22s33
56
#2. With Recursion
Now we will see another way of implementing this, using recursion.
def sumOfNumbers(string, n, temp, sums):
curr_val = string[n]
if( curr_val.isalpha() ):
sums = sums + int(temp)
temp = 0
else:
temp = str(temp) + str(curr_val)
if n == 0:
return sums
else:
return sumOfNumbers(string, n-1, temp, sums)
string = input("Enter a Alpha Numeric String: ")
n = len(string) - 1
print( sumOfNumbers(string, n, temp=0, sums=0) )
Enter an Alpha-Numeric String: study24tonight77
101
2. Code for Sum of all Digits In Alpha-Numberic String
Here the algorithm is very simple, just add the value to the sum only if it is a numeric value and finally print sum. In this case, for string s1s22s33, digits are 1, 2, 2, 3 and 3.
#1 Without Recursion
string = input("Enter a Alpha-Numeric String: ")
sums = 0
for i in string:
if( i.isnumeric() ):
sums = sums+int(i)
print(sums)
Enter an Alpha-Numeric String: a11s22s55
16
#2 Using Recursion
def sumOfNumbers(string, n, sums):
curr_val = string[n]
if( curr_val.isnumeric() ):
sums = sums + int(curr_val)
if n == 0:
return sums
else:
return sumOfNumbers(string, n-1, sums)
string = input("Enter a Alpha Numeric String: ")
n = len(string) - 1
print( sumOfNumbers(string, n, sums=0) )
Enter an Alpha-Numeric String: study24tonight77
20
Conclusion:
Pheww! This is a brief explanation of how to find the sum of all numbers and digits in an alpha-numeric string in python. I hope that you enjoyed the post. If you feel that this post is useful, please share it with your friends and colleagues.
Thanks for reading it till the end.
You may also like: