Mymood
Mymood

Reputation: 3

How can i calculate sum of all numbers in text with python?

input essum magis 45 kohlrabi azuki bean garlic. Dandelion cucumber -1 earthnut pea peanut water 10.5 spinach fennel kombu maize bamboo shoot green

output 54.5

explanation 45 + 10.5 -1 = 54.5

I'm not allowed to import packages yet! im really lost i have been working on this for the 4 hours

n = input('Enter an Alpha-Numeric String: ')
n_sum = 0
temp_num = ''
for i in n:
    if i.isalpha():
        if temp_num != '':
            n_sum = n_sum + int(temp_num)
            temp_num = 0
else:
    temp_num = str(temp_num) + str(i)

if temp_num != '':
    n_sum = n_sum + int(temp_num)
    temp_num = 0

print(n_sum) 

Upvotes: 0

Views: 52

Answers (1)

001
001

Reputation: 13533

Split the sentence on space. Check if each word is a number. If it is, convert to a number and add to total:

n = input('Enter an Alpha-Numeric String: ')
n_sum = 0
for word in n.split():
    try:
        n_sum += float(word)
    except ValueError:
        # float() will throw an exception if not a number
        pass
print(n_sum)

Upvotes: 2

Related Questions