Python Program to Compute Sum of Digits in a String

In this post, we will write a Python program to compute the sum of digits in a string. The string will be given as input and the program compute the sum of digits using various methods. We are using the For Loop and if-else statement to compute the sum of digits.

Example of the sum of digits in a string:-
String: 5Py8thon3
Sum of digits = 16

Write a Python Program to Compute Sum of Digits of a Given String

We will take a string while declaring the variables. Then, compute the sum of digits in a given string using the for loop and if-else statement. The isdigit() is a built-in method used for string handling. The isdigit() method returns True if the characters are digits, otherwise False. We can check if one character is a digit or not. If it is a digit, we will add its value to the sum_digit variable.

# python program to compute sum of digits in a string

# take input
string = input("Enter any string: ")

# find sum of digits
sum_digit = 0
for x in string:
    if x.isdigit():
        sum_digit += int(x)

# display result
print("Sum of digits =", sum_digit)

Output for the different input values:-

Enter any string: 5Python3
Sum of digits = 8

Enter any string: K1n0w5pro86g7am125
Sum of digits = 35

Sum of Digits in a String in Python

This python program doing the same thing but a different way in this program, we will compute the sum of digits in one line code. We are also using the sum() function. The sum() function adds the items of an iterable and returns the sum.

# python program to compute sum of digits in a string

# take input
string = input("Enter any string: ")

# find sum of digits
sum_digit = sum(int(x) for x in string if x.isdigit())

# display result
print("Sum of digits =", sum_digit)

Output:-

Enter any string: sum16of9di2gi7t
Sum of digits = 25

Python Program to Find Sum of Digits in a String

In the previous program, we used isdigit() function to check digits in a string but in this program, we are using Regular Expression (RegEx module) to check digits in the string.

# python program to compute sum of digits in a string

# importing RegEx module
import re

# take input
string = input("Enter any string: ")

# find sum of digits
sum_digit = sum(int(x) for x in re.findall(r'[0-9]', string))

# display result
print("Sum of digits =", sum_digit)

Output:-

Enter any string: R64e3gE87x5
Sum of digits = 33

Also See:- Sum of Digits of a Number in Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *