Search code examples
pythonstringsplitlogicslice

I want the sum of numbers given in a string in python


**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.


Solution

  • 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