DGC
DGC

Reputation: 13

Sum of parts of a string in Python

I'm learning to program using the book "Introduction to computation and programming using Python" by John V. Guttag. There is an exercise on it that says the following:

'Finger exercise: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s.'

My try was:

#Finger exercise [MIT] PAGE 42     12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
    total = 0
    for l in range(0,len(s)):
        if s[l] == ',':
            c = l + 1
            while s[c] != ',':
                c = c + 1
                if s[c] == ',':
                    total = total + int(s[int(l),int(c)])
print total

but it keeps showing this error

TypeError: string indices must be integers, not tuple

I've tried to seek solutions online but only found solutions that work but not with the content I already now. Any help?

Upvotes: 1

Views: 784

Answers (4)

Majed
Majed

Reputation: 1

total = ''
s = '1.23, 2.4, 3.123'
n = 0.0
for i in s:
    if i != ',':
        total = total + i   
    else: 
        n =  float(total) + n
        total = ''
n = float(total) + n
print(n)

Upvotes: 0

Rafael Amador
Rafael Amador

Reputation: 1

A solution I found, hope its useful:

s = "1.23, 2.4, 3.123"

news = s.split(",")

total = 0 

for string in range(len(news)):    
    total += float(news[string])

print(total)

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

First of all, there is no processing of anything before the first comma.

Next, you should comment each part of it at least initially to you are clear what each line is doing.

You shouldn't need to check for a ',' in multiple places, keep a variable.

Upvotes: 0

poke
poke

Reputation: 387607

You are creating a tuple when accessing your string item here:

s[int(l),int(c)]

Commas generally create tuples.

Instead, you want to use a slice here using a colon:

s[int(l):int(c)]

Note that both variables are already integers, so you don't actually need to convert them:

s[l:c]

Also note that you are summing integer values although you accept floats as the input. So instead of adding int(s[l:c]) you want to add float(s[l:c]).

Upvotes: 1

Related Questions