简体   繁体   中英

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) 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM