Problems convert string into float


#1

Hi there, im a beginner in coding and decided to start with python.

i have a problem in a course in Python: Python Objects

i have a list with prices:
list = [’$1.21’, ‘$4.50’, ‘$1.20’, ‘$3.57’ etc. ]

because of the dollar sign “$” each element is a string. But now, i have to strip the dollar sign and convert the string to a float. Finally i have to add all prices into total_sales.

i write the code:

total_sales = 0
for price in sales:
price.strip("$")
float(price)
total_sales += price

print(total_sales)

i got a ValueError:
ValueError: could not convert string to float: ‘$1.21’

So i dont understand why my code is wrong and “price” cannot strip the dollar sign with .strip("$").

It would be nice if someone can help me.
Thank you


#2

looking at the documentation:

https://docs.python.org/2/library/string.html#string.strip

we learn that strip returns a copy of the string with the character(s) removed. You do nothing with the returned result.


#3

Thank you very much @stetim94

Now my code looks like:

for price in sales:
z = price.strip("$")
total_sales += float(z)

and it works. :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.