Computer Science, asked by kunchapuhema000, 10 hours ago

Input: Var="abc 123h 895jkl 12z"
Output:1030(123+895+12)​

Answers

Answered by anindyaadhikari13
4

\texttt{\textsf{\large{\underline{Solution}:}}}

The given co‎de is written in Python.

str=input("Enter a string: ")

sum,nums=0,'0'

for i in str:

 if i.isdigit():

   nums+=i

 else:

   sum+=int(nums)

   nums='0'

sum+=int(nums)

print("Sum of the numbers in the given string is:",sum)

Logic for the co‎de -

  • Input the string from the user.
  • Initialize sum = 0.
  • Find the numbers in the string and add to the sum.
  • Display the sum.

We can also solve it easily using re module. RE stands for Regular Expression. It is used to check whether a string contains a specific pattern.

Lets do it!

import re

pattern=r'\d+'

str=input("Enter string: ")

numbers=re.findall(pattern,str)

numbers=list(map(lambda _:int(_),numbers))

sum=sum(numbers)

print("Sum of the numbers present in the string is:",sum)

1. We have to import re module to solve this.

2. pattern (line 2): Specifies the string we have to extract (i.e., the number)

3. findall() finds all the string that matches the pattern.

4. Since, the numbers are stored in string format, we have to convert them to int which is solved using map() fu‎nction.

5. Then, using sum() fu‎nction, sum of the numbers is calculated.

See the attachments for output.

Attachments:
Similar questions