KnowledgeBoat Logo

Computer Science

Write a program that does the following :

  • takes two inputs : the first, an integer and the second, a string
  • from the input string extract all the digits, in the order they occurred, from the string.
    • if no digits occur, set the extracted digits to 0
  • add the integer input and the digits extracted from the string together as integers
  • print a string of the form :
    "integerinput + stringdigits = sum"

For example :
For inputs 12, 'abc123' → '12 + 123 = 135'
For inputs 20, 'a5b6c7' → '20 + 567 =587'
For inputs 100, 'hi mom' → '100 + 0 = 100'

Python

Python String Manipulation

6 Likes

Answer

num = int(input("Enter an integer: "))
str = input("Enter the string: ")

digitsStr = ''
digitsNum = 0;

for ch in str :
    if ch.isdigit() :
        digitsStr += ch

if digitsStr :
    digitsNum = int(digitsStr)

print(num, "+", digitsNum, "=", (num + digitsNum))

Output

Enter an integer: 12
Enter the string: abc123
12 + 123 = 135

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

Enter an integer: 20
Enter the string: a5b6c7
20 + 567 = 587

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

Enter an integer: 100
Enter the string: hi mom
100 + 0 = 100

Answered By

1 Like


Related Questions