Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert String Literal to Float

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.

like image 528
user3211293 Avatar asked Jan 19 '14 03:01

user3211293


4 Answers

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)
like image 92
thefourtheye Avatar answered Oct 16 '22 01:10

thefourtheye


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
like image 39
Christian Tapia Avatar answered Oct 16 '22 01:10

Christian Tapia


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))
like image 43
Per-Mikael Bruvik Avatar answered Oct 16 '22 01:10

Per-Mikael Bruvik


total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
    total = total + float(c)
print(total)
like image 28
user5716300 Avatar answered Oct 16 '22 01:10

user5716300