Python Convert String Literal to Float
Asked Answered
M

24

5

I am working through the book "Introduction to Computation and Programming Using Python" by Dr. Guttag. I am working on the finger exercises for Chapter 3. I am stuck. It is section 3.2, page 25. The exercise is: 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 sume of the numbers in s.

The previous example was:

total = 0
for c in '123456789':
    total += int(c)
print total.

I've tried and tried but keep getting various errors. Here's my latest attempt.

total = 0
s = '1.23,2.4,3.123' 
print s
float(s)
for c in s:
    total += c
    print c
print total    
print 'The total should be ', 1.23+2.4+3.123

I get ValueError: invalid literal for float(): 1.23,2.4,3.123.

Midyear answered 19/1, 2014 at 3:3 Comment(2)
conert string to float using >>> a = "1.23" float(a) >>1.23. If multiple string like in your case then split them and use float function.Grimaldi
One hint: look at the snippet total += c. c is a string, so you're trying to add a string to an integer, total.Abba
K
6

Floating point values cannot have a comma. You are passing 1.23,2.4,3.123 as it is to float function, which is not valid. First split the string based on comma,

s = "1.23,2.4,3.123"
print s.split(",")        # ['1.23', '2.4', '3.123']

Then convert each and and every element of that list to float and add them together to get the result. To feel the power of Python, this particular problem can be solved in the following ways.

You can find the total, like this

s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))

If the number of elements is going to be too large, you can use a generator expression, like this

total = sum(float(item) for item in s.split(","))

All these versions will produce the same result as

total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
    total += float(current_number)
Kotto answered 19/1, 2014 at 3:7 Comment(2)
May I ask: What is the difference between total = sum([float(item) for item in s.split(",")]); and total = sum(float(item) for item in s.split(","))Pachysandra
@KennyLJ First one uses List Comprehension, and the second one uses Generator ExpressionKotto
H
4

Since you are starting with Python, you could try this simple approach:

Use the split(c) function, where c is a delimiter. With this you will have a list numbers (in the code below). Then you can iterate over each element of that list, casting each number to a float (because elements of numbers are strings) and sum them:

numbers = s.split(',')
sum = 0

for e in numbers:
    sum += float(e)

print sum

Output:

6.753
Hey answered 19/1, 2014 at 3:7 Comment(0)
M
3

From the book Introduction to Computation and Programming using Python at page 25.

"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."

If we use only what has been taught so far, then this code is one approach:

tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
    if ch != ',':
        tmp = tmp + ch
    elif ch == ',':
        num = num + float(tmp)
        tmp = ''

# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))
Milagro answered 18/7, 2014 at 10:25 Comment(0)
E
2
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
    total = total + float(c)
print(total)
Econometrics answered 25/12, 2015 at 8:34 Comment(0)
Q
1

Works Like A Charm Only used what i have learned yet

    s = raw_input('Enter a string that contains a sequence of decimal ' +  
                   'numbers separated by commas, e.g. 1.23,2.4,3.123: ')

    s = "," + s+ "," 

    total =0

    for i in range(0,len(s)):

         if s[i] == ",":

              for j in range(1,(len(s)-i)):

                   if s[i+j] == ","
                   total  = total + float(s[(i+1):(i+j)])
                   break
     print total
Queenie answered 11/9, 2015 at 17:53 Comment(0)
A
1

This is what I came up with:

s = raw_input('Enter a sequence of decimal numbers separated by commas: ')
aux = ''
total = 0
for c in s:
    aux = aux + c
    if c == ',':
        total = total + float(aux[0:len(aux)-1])
        aux = ''
total = total + float(aux) ##Uses last value stored in aux
print 'The sum of the numbers entered is ', total
Apiary answered 14/5, 2017 at 18:37 Comment(1)
Try to explain what you have done in detail rather than assuming the code is enough explanation.Yearn
K
1

I think they've revised this textbook since this question was asked (and some of the other's have answered.) I have the second edition of the text and the split example is not on page 25. There's nothing prior to this lesson that shows you how to use split.

I wound up finding a different way of doing it using regular expressions. Here's my code:

# Intro to Python
# Chapter 3.2
# Finger Exercises

# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
    total = total + float(s)
print(total)

I've never considered myself dense when it comes to learning new things, but I'm having a hard time with (most of) the finger exercises in this book so far.

Kress answered 9/8, 2018 at 20:33 Comment(0)
W
1
s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
    if c != ',':
        x = x + c
    else:
        sum = sum + float(x)
        x = ''  
sum = sum + float(x)        
print(sum)  

This is using just the ideas already covered in the book at this point. Basically it goes through each character in the original string, s, using string addition to add each one to the next to build a new string, x, until it encounters a comma, at which point it changes what it has as x to a float and adds it to the sum variable, which started at zero. It then resets x back to an empty string and repeats until all the characters in s have been covered

Weakkneed answered 11/2, 2019 at 22:54 Comment(0)
S
0

Here's a solution without using split:

s='1.23,2.4,3.123,5.45343'
pos=[0]
total=0
for i in range(0,len(s)):
    if s[i]==',':
        pos.append(len(s[0:i]))
pos.append(len(s))
for j in range(len(pos)-1):
    if j==0:
        num=float(s[pos[j]:pos[j+1]])
        total=total+num
    else:
        num=float(s[pos[j]+1:pos[j+1]])
        total=total+num     
print total
Stallard answered 8/12, 2014 at 5:28 Comment(0)
S
0

My way works:

s = '1.23, 211.3'
total = 0
for x in s:
    for i in x:
        if i != ',' and i != ' ' and i != '.':
            total = total + int(i)
print total
Sign answered 18/1, 2015 at 20:20 Comment(1)
You are adding all the ints in the string, not two floats!Priestcraft
D
0

My answer is here:

s = '1.23,2.4,3.123'

sum = 0
is_int_part = True
n = 0
for c in s:
    if c == '.':
        is_int_part = False
    elif c == ',':
        if is_int_part == True:
            total += sum
        else:
            total += sum/10.0**n
        sum = 0
        is_int_part = True
        n = 0
    else:
        sum *= 10
        sum += int(c)
        if is_int_part == False:
            n += 1
if is_int_part == True:
    total += sum
else:
    total += sum/10.0**n
print total
Deidredeific answered 14/3, 2015 at 7:56 Comment(0)
R
0

I have managed to answer the question with the knowledge gained up until 3.2 the section for loop

s = '1.0, 1.1, 1.2'
print 'List of decimal number' 
print s 
total = 0.0
for c in s:
    if c == ',':
       total += float(s[0:(s.index(','))])
       d = int(s.index(','))+1
       s = s[(d+1) : len(s)]

s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total  

This is the answer to the question i feel that the split function is not good for beginner like you and me.

Reach answered 4/2, 2016 at 9:36 Comment(0)
C
0

Considering the fact that you might not yet be exposed to more complex functions, simply try these out.

total = 0
for c in "1.23","2.4",3.123":
    total += float(c)
print total
Calash answered 8/5, 2017 at 4:34 Comment(0)
B
0

My answer:

s = '2.1,2.0'
countI = 0
countF = 0
totalS = 0

for num in s:
    if num == ',' or (countF + 1 == len(s)):
        totalS += float(s[countI:countF])
        if countF < len(s):
            countI = countF + 1
    countF += 1

print(totalS) # 4.1

This only works if the numbers are floats

Beseech answered 2/7, 2017 at 22:9 Comment(0)
B
0

Here is my answer. It is similar to the one by user5716300 above, but since I am also a beginner I explicitly created a separate variable s1 for the split string:

s = "1.23,2.4,3.123"
s1 = s.split(",")      #this creates a list of strings

count = 0.0
for i in s1:
    count = count + float(i)
print(count)
Barcot answered 2/12, 2018 at 16:3 Comment(0)
M
0

If we are just sticking with the content for that chapter, I came up with this: (though using that sum method mentioned by theFourthEye is also pretty slick):

s = '1.23,3.4,4.5'
result = s.split(',')
result = list(map(float, result))
n = 0
add = 0
for a in result:
    add = add + result[n]
    n = n + 1
print(add)
Measures answered 26/1, 2019 at 4:46 Comment(0)
K
0

I just wanna to post my answer because I am reading this book now.

s = '1.23,2.4,3.123'

ans = 0.0
i = 0
j = 0
for c in s:
    if c == ',':
        ans += float(s[i:j])
        i = j + 1
    j += 1
ans += float(s[i:j])
print(str(ans))
Kana answered 12/2, 2020 at 2:21 Comment(0)
N
0

Using knowledge from the book:

s = '4.58,2.399,3.1456,7.655,9.343'
total = 0
index = 0
for string in s:
    index += 1
    if string == ',':
        temp = float(s[:index-1])
        s = s[index:]
        index = 0
        total += temp
        temp = 0
print(total)

Here I used string slicing, and by slicing the original string every time our 'string' variable is equal to ','. Also using an index variable to keep track of the number that is before the comma. After slicing the string, the number that gets input into tmp is cleared with the comma in front of it, the string becoming another string without that number.

Because of this, the index variable needs to be reset every time this happens.

Nationalize answered 20/4, 2020 at 18:34 Comment(0)
P
0

Here's mine using the exact string in the question and only what has been taught so far.

total = 0
temp_num = ''

for char in '1.23,2.4,3.123':
    if char == ',':
        total += float(temp_num)
        temp_num = ''
    else:
        temp_num += char

total += float(temp_num) #to catch the last number that has no comma after it

print(total)
Priestcraft answered 9/7, 2021 at 15:28 Comment(0)
D
0

I know this isn't covered in the book up to this point but I happened to learn the use of the eval() function on my own prior to getting to this question and used it to solve.

total = 0
s = "1.23,2.4,3.123"
x = eval(s)
y = sum(x)
print(y)
Dispenser answered 16/2, 2022 at 0:34 Comment(0)
P
0

Here's mine using the exact string in the question and only what has been taught so far.

s=str(input("Enter a serie of numbers: "))
list=s+","
total=0.0
num=""
for c in list:
    if c!="," :
        num=num+c
    else:
        total=total+float(num)
        num=""
print("The sum of ",s," is ",total)
Papilionaceous answered 14/3, 2023 at 23:10 Comment(0)
I
-1

I think this is the easiest way to answer the question. It uses the split command, which is not introduced in the book at this moment but a very useful command.

s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
sList = s.split(',') #create a list of these values
print(sList) #to check if list is correctly created

total = 0 #for creating the variable

for each in sList: 
    total = total + float(each)

print(total)
Isomerize answered 21/1, 2019 at 19:6 Comment(1)
What does your answer add to several existing identical answers?Actinolite
S
-1
s = '1.23,2.4,3.123'
x = ''
sum = 0
for i in s:
    if i == ',':
        sum = sum + float(x)
        x = ''
    else:
        x = x + i
sum = sum + float(x) #because the last number doesn't have a comma at the end, so it'll not be added in the for loop
print(sum)
Skijoring answered 18/8, 2023 at 20:30 Comment(1)
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?Hautboy
A
-2
total =0
s = {1.23,2.4,3.123}
for c in s:
    total = total+float(c)
print(total)
Antitrades answered 2/12, 2017 at 5:19 Comment(1)
This does not answer the original question.Deficiency

© 2022 - 2025 — McMap. All rights reserved.