#### [SOLVED] Sum space-separated integers as string in a list

I currently have this list: `['5 4 7', '4 3 1', '6 8 4'', '4 8 6']` Note that not all numbers are separated by commas.

I would like to be able to calculate the total for each section of the list. For example, the first calculation should be 5+4+7 to give me 16. I would just like to know how to convert this list to be able to do maths calculations with the numbers.

#### @Jean-François Fabre 2018-03-13 15:50:59

split your strings, map to integer and perform `sum` on the resulting inputs, in a list comprehension:

``````>>> [sum(map(int,x.split())) for x in ['5 4 7', '4 3 1', '6 8 4', '4 8 6']]
[16, 8, 18, 18]
``````

(works for negative values as well :))

#### @sam smith 2018-03-13 15:58:58

Yes thank you. I was trying to do it in that method after searching around but I kept getting errors.

#### @Ajax1234 2018-03-13 15:58:12

You can also use regex:

``````import re
s = ['5 4 7', '4 3 1', '6 8 4', '4 8 6']
new_s = [sum(map(int, re.findall('\d+', b))) for b in s]
``````

Output:

``````[16, 8, 18, 18]
``````

However, if every digit is a single character, then you can use `isdigit()`:

``````last_result = [sum(map(int, filter(lambda x:x.isdigit(), i))) for i in s]
``````

### [SOLVED] Finding the index of an item given a list containing it in Python

• 2008-10-07 01:39:38
• Eugene M
• 2701639 View
• 2334 Score
• Tags:   python list

### [SOLVED] How do I list all files of a directory?

• 2010-07-08 19:31:22
• duhhunjonn
• 2580246 View
• 2928 Score
• Tags:   python directory

### [SOLVED] How do I check if a list is empty?

• 2008-09-10 06:20:11
• Ray Vega
• 1821136 View
• 2818 Score
• Tags:   python list is-empty

### [SOLVED] Converting integer to string in Python?

• 2009-06-07 10:22:38
• Hick
• 2566342 View
• 1027 Score
• Tags:   python

### [SOLVED] How to print number with commas as thousands separators?

• 2009-11-30 23:11:43
• Elias Zamaria
• 274164 View
• 503 Score
• Tags:   python python-2.x