KnowledgeBoat Logo

Computer Science

Write a program that should do the following :

  • prompt the user for a string
  • extract all the digits from the string
  • If there are digits:
    • sum the collected digits together
    • print out the original string, the digits, the sum of the digits
  • If there are no digits:
    • print the original string and a message "has no digits"

Sample

  • given the input : abc123
    prints abc123 has the digits 123 which sum to 6
  • given the input : abcd
    prints abcd has no digits

Python

Python String Manipulation

20 Likes

Answer

str = input("Enter the string: ")
sum = 0
digitStr = ''
for ch in str :
    if ch.isdigit() :
        digitStr += ch
        sum += int(ch)
if not digitStr :
    print(str, "has no digits")
else :
    print(str, "has the digits", digitStr, "which sum to", sum)

Output

Enter the string: abc123
abc123 has the digits 123 which sum to 6

=====================================

Enter the string: KnowledgeBoat
KnowledgeBoat has no digits

Answered By

14 Likes


Related Questions