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
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
Related Questions
Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places.)
Write a Python program as per specifications given below:
- Repeatedly prompt for a sentence (string) or for 'q' to quit.
- Upon input of a sentence s, print the string produced from s by converting each lower case letter to upper case and each upper case letter to lower case.
- All other characters are left unchanged.
For example,
Please enter a sentence, or 'q' to quit : This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q ' to quit : What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q' to quit : qWrite a program which reverses a string and stores the reversed string in a new string.
Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s) :
- Number of words
- Number of characters (including white-space and punctuation)
- Percentage of characters that are alphanumeric
Hints
- Assume any consecutive sequence of non-blank characters is a word.