0

**String1='Deepak25 is awesome5'** #I want the sum of numbers i.e. 30 as output. Sum=30

String2='I am 25 years and 10 months old'
Sum = 35`

for String2 I have used string split method and calculated the Sum. But for String1 I am not able to do it. Is there a way to calculate Sum.

1 Answers1

3

You can use regex to find all the integer in the string.
https://www.pythontutorial.net/python-regex/python-regex-findall/
Once you have the list, cast it to integer then sum all the elements
https://www.geeksforgeeks.org/python-converting-all-strings-in-list-to-integers/

import re
String1='Deepak25 is awesome5'
String2='I am 25 years and 10 months old'
 #create pattern, only number, any length
p = re.compile('[0-9]+')
 #get the list of all match
l = re.findall(p, String2)
 #cast to int and sum the list
result = sum([int(x) for x in l])

print(result)
 # output : 30 for String 1 | 35 for String2

Of course you'll have to create a function with that to implement it in a clean way :)
Note that this won't work with floating point number, you'll have to modify the regex pattern

tstx
  • 151
  • 2
  • 12
  • 1
    `eval` instead of `int`? [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – B Remmelzwaal Apr 28 '23 at 08:23
  • 1
    Sure, this bring nothing and makes it more confusing, I'll edit the answer. – tstx Apr 28 '23 at 08:29