Skip to content
Programming Problems · Q4

Q.Input a string having some digits. Write a function to return the sum of digits present in this string.

Rajasthan RbseTextbookSubjective· 3mImportance★★★★★est
92% · 12/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Walk the string once; ch.isdigit() picks out digit characters, int(ch) converts each to its numeric value, and a running total accumulates the sum.

Idea. The string mixes letters, digits and possibly symbols. A digit inside a string is a character ('7'), not a number, so two things are needed per character: a test — isdigit() — and a conversion — int(). Everything that is not a digit is skipped.

Algorithm

  1. Set total = 0.
  2. For every character ch in the string: if ch.isdigit(), do total += int(ch).
  3. Return total.
def sumDigits(st):
    """Return the sum of all digits present in string st."""
    total = 0
    for ch in st:
        if ch.isdigit():
            total += int(ch)   # '7' -> 7
    return total

# main program
s = input("Enter a string having digits: ")
print("Sum of digits in the string:", sumDigits(s))

Trace for st = "Class11Python3":

chisdigit()?total
C,l,a,s,sno0
1yes1
1yes2
P,y,t,h,o,nno2
3yes5

Sample runs

Enter a string having digits: Class11Python3
Sum of digits in the string: 5
Enter a string having digits: a1b2c3d4 …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.