简体   繁体   中英

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: ','* 

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.

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

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

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

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

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