Python Program to Compute Sum of Digits of a Given string

In this example, we will write a simple program to take input string from the user and calculate the sum of the given digits in the string. To better understand this example, make sure you have knowledge of the following tutorials:-

Python Program to Compute Sum of Digits of a Given string

inputstr = input("Enter your string: ")
sum_total = 0
for x in inputstr:
    if x.isdigit():
        sum_total += int(x)


print("Total:- ", sum_total)

The output of the above program is:-

Enter your string: ab1234sdf4978
Total:- 38

Program Explanation

The user provides the string containing alphabets and numbers to which the sum needs to be generated.  The sum is initialized to 0 at the beginning of the program. For loop iterates through each of the characters and isdigit() method is used to check if the character is a number. If the character is found as a number, then it is added to our sum variable. The final result is printed using the print function in Python.

SHARE Python Program to Compute Sum of Digits of a Given string

You may also like...

Leave a Reply

Your email address will not be published.

Share