Jun Fai Heu
Jun Fai Heu

Reputation: 41

How to add all numbers in a single line of string

I have a line which have a few digits combined with some words.

      1       1       1 Old -> New

I want to add all numbers to a variable. May I know how to do it? Thanks

Upvotes: 1

Views: 183

Answers (2)

Anas Alzogbi
Anas Alzogbi

Reputation: 43

You can use RegEx to extract the numbers from the text, cast them to integers, add them to a list and sum over the list elements:

import re
text = '      1       1       1 Old -> New'   
sum([int(i) for i in re.findall('\d+', text)])

Upvotes: 2

lenik
lenik

Reputation: 23536

text = '      1       1       1 Old -> New'
nums = []
for t in text.split() :
    try :
        nums.append( int(t) )
    except ValueError:
        pass

print( sum(nums) )

3

Upvotes: 1

Related Questions