Alvin van der Kuech
Alvin van der Kuech

Reputation: 35

convert string numbers separated by comma to integers or floats in python

I am very super new at Python and I've run into a problem. I'm trying to convert a string of numbers into an int or float so that I can add them up. This is my first question/post. Any suggestions are greatly appreciated!

total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'

for i in s:
    total += int(i)
print total

I get the errors:

      *3 
      4 for i in s:
----> 5     total += int(i)
      6 print total

ValueError: invalid literal for int() with base 10: ','* 

Upvotes: 1

Views: 7559

Answers (5)

liyuanhe211
liyuanhe211

Reputation: 701

How about this? (^_^)

In[3]: s = '2, 3.4, 5, 3, 6.2, 4, 7'
In[4]: s = s.replace(",","+") # s = '2+ 3.4+ 5+ 3+ 6.2+ 4+ 7'
In[5]: total = eval(s)
In[6]: print(total)
30.6

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52071

You have a string of comma separated float values and not int. You need to split them first and then add them. You need to cast it to float and not int

total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'

for i in s.split(','):
    total += float(i)
print total

Output will be 30.6

Upvotes: 3

senshin
senshin

Reputation: 10360

You'll want to split the string at the commas using str.split. Then, convert them to floats (I don't know why you're using int when you say that you want to convert them to "an int or float").

total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'
for i in s.split(','):
    total += float(i)
print total

Personally, I would prefer to do this with a generator expression:

s = '2, 3.4, 5, 3, 6.2, 4, 7'
total = sum(float(i) for i in s.split(','))
print total

The reason what you're doing doesn't work is that for i in s iterates over each individual character of s. So first it does total += int('2'), which works. But then it tries total += int(','), which obviously doesn't work.

Upvotes: 5

sedavidw
sedavidw

Reputation: 11691

You want to split the string

total = 0
for i in s.split(','):
    i = float(i) #using float because you don't only have integers
    total += i

Upvotes: 0

taesu
taesu

Reputation: 4570

Here is my approach.

total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'
lst = s.split(',');
for i in lst:
    i = float(i)
    total += i
print total

Upvotes: 0

Related Questions