Advertisements
Advertisements
Question
Input a string having some digits. Write a function to return the sum of digits present in this string.
Answer in Brief
Advertisements
Solution
Program:
#sumDigit function to sum all the digits
def sumDigit(string):
sum = 0
for a in string:
#Checking if a character is digit and adding it
if(a.isdigit()):
sum += int(a)
return sum
userInput = input("Enter any string with digits: ")
#Calling the sumDigit function
result = sumDigit(userInput)
#Printing the sum of all digits
print("The sum of all digits in the string '",userInput,"' is:",result)
OUTPUT:
Enter any string with digits: The cost of this table is Rs. 3450
The sum of all digits in the string ' The cost of this table is Rs. 3450 ' is: 12shaalaa.com
String
Is there an error in this question or solution?
