naz115
naz115

Reputation: 21

having trouble converting string to float and adding from list (python)

I'm trying to convert this list of numbers (that are strings) into floats so I can do an analysis with them. However, I receive an error when trying to convert them to float.

This is the list:

temp_gallons = ['404,443.60 ', '367,223.12 ', '388,369.08 ', '352,472.56 ', '386,618.76 ', '333,929.64 ', '326,868.52 ', '257,663.56 ', '0.00 ', '0.00 ', '0.00 ', '0.00 ', '2,817,589 ']

This is the for loop iteration for adding them while temporarily converting them into a float:

Q1_Gallons = 0.0
for i in range(0,2):
  Q1_Gallons = Q1_Gallons + float(temp_gallons[i])

I figured the reason was because there is a white space at the end of each number. So I tried stripping the values using a for loop iteration:

for i in temp_gallons:
  i.strip(" ")

However, the list remains the same after the strip and I still cannot convert the string to float and/or add the numbers.

Just for context: these are values for each month and I am making a quarterly savings analysis adding the values for the first three months, next three, and so forth.

Upvotes: 0

Views: 306

Answers (2)

Ram
Ram

Reputation: 4789

The reason is not the trailing spaces but the , in between.

You have to remove the , from the strings and then convert to float.

Here's how to do it.

temp_gallons = ['404,443.60 ', '367,223.12 ', '388,369.08 ', '352,472.56 ', '386,618.76 ', '333,929.64 ', '326,868.52 ', '257,663.56 ', '0.00 ', '0.00 ', '0.00 ', '0.00 ', '2,817,589 ']

temp_gallons = [float(x.replace(',', '')) for x in temp_gallons]
print(temp_gallons)
[404443.6, 367223.12, 388369.08, 352472.56, 386618.76, 333929.64, 326868.52, 257663.56, 0.0, 0.0, 0.0, 0.0, 2817589.0]

Upvotes: 2

Asir Shahriar Roudra
Asir Shahriar Roudra

Reputation: 360

Firstly, you are getting errors because there is a comma in the string. Float cant convert a comma into a floating number. Secondly, the space is not a problem. Suppose you have two strings S1 = '123.00 '(there is a space), S2 = '12,324324' (there is a comma) . You can use float() to convert S1 to a float but can't use float() on S2 because there is a "," there. You have to remove it first. Check the code:

temp_gallons = ['404,443.60 ', '367,223.12 ', '388,369.08 ', '352,472.56 ', '386,618.76 ',
                '333,929.64 ', '326,868.52 ', '257,663.56 ', '0.00 ', '0.00 ', '0.00 ', '0.00 ', '2,817,589 ']

temp_gallons_float = []

for i in temp_gallons:
    i = i.replace(',', '')
    i = float(i)
    temp_gallons_float.append(i)

print(temp_gallons_float)


# for adding

Q1_Gallons = 0.0

for i in temp_gallons_float:
    Q1_Gallons += i

print(Q1_Gallons)

Upvotes: 1

Related Questions