Input a string having some digits. Write a function to return the sum of digits present in this string.
Question
Input a string having some digits. Write a function to return the sum of digits present in this string.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a Python function to sum the digits present in a given string:
def sum_of_digits(s):
total = 0
for char in s:
if char.isdigit():
total += int(char)
return total
# Example usage
s = input("Enter a string: ")
result = sum_of_digits(s)
print("The sum of digits in the string is:", result)
This function works as follows:
Initialize a total sum to 0.
Iterate through each character in the string.
Check if the character is a digit using the
isdigit()
method.If it is a digit, convert it to an integer and add it to the total sum.
Finally, return the total sum.
Example:
Input:
Hello123
Output:
6
(since 1 + 2 + 3 = 6)
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month