Reputation: 41
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
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
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