Find the sum of numbers present in a string separated by spaces in between using python

I am finding it difficult in writing python code for the below scenario

I have a list called

sume=['12 1929 8827','8837 139']

I converted the string to int but it is showing error because of the " " in between.

How to calculate the sum of the digits by eliminating the " " in between.

Answer should be 19744.

Upvotes: 0

Views: 3920

Answers (5)

Léopold Houdin
Léopold Houdin

Reputation: 1525

Something like:

parsed = []
array = ['12 1929 8827','8837 139']
for string in array:
    for component in string.split(' '):
        parsed.append(int(component))

sum = reduce(lambda a, x: a + x, parsed)

Or more simply (as pointed out by @wwii):

parsed = []
array = ['12 1929 8827','8837 139']
for string in array:
    for component in string.split(' '):
        parsed.append(int(component))

sum = sum(parsed)

Or even more simply (also as pointed out by @wwii):

accumulated = 0
array = ['12 1929 8827','8837 139']
for string in array:
    for component in string.split(' '):
        accumulated += int(component)

sum = sum(parsed)

Upvotes: 1

Tolqinbek Isoqov
Tolqinbek Isoqov

Reputation: 175

Simple solution is sum(map(int, ' '.join(sume).split()))

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You need to split by space and sum those numbers, one approach is the following:

sum(number for word in ['12 1929 8827','8837 139'] for number in map(int, word.split()))

Output

19744

A more robust approach is to provide a default value in case the cast fails:

def to_int(text, default=0):
    try:
        return int(text)
    except ValueError:
        return default

text_numbers = ['12 1929 8827','8837 139']

print(sum(number for word in text_numbers for number in map(to_int, word.split())))

Output

19744

Upvotes: 1

N Chauhan
N Chauhan

Reputation: 3515

Use the str.split() method to split by space:

total = sum(sum(int(n) for n in i.split())
            for i in sume)
#                    ^^ that's your starting list

This takes each string on numbers in the list and splits it by space, returning the sum of it. Then each of these 'sums' are fed into the outer sum call to get their total. This would look like the following when expanded:

total = 0
for i in sume:
    i = i.split()
    for n in i:
        total += int(n)

Remember that split() returns a list of strings, so you still need to cast each item to int before summing it.

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

Use sum+map and str.split()

>>> sume=['12 1929 8827','8837 139']
>>> elems = [sum(map(int, s.split())) for s in sume]
[10768, 8976]

If you need the sum of all elements, can use sum again

>>> sum(elems)
19744

Upvotes: 1

Related Questions