Home > Software design >  How to convert str to a float?
How to convert str to a float?

Time:08-02

I imported a list full of floats as strings, and i tried to convert them to floats, but this error kept popping up

Traceback (most recent call last):
  File "c:\Users\peter\Documents\coding\projects\LineFitting.py", line 11, in <module>
    StockPriceFile[value] = float(StockPriceFile[value])
ValueError: could not convert string to float: '[36800.]'

this is what i did to try and convert the list:

#1
for value in range(0, len(StockPriceFile)):
    StockPriceFile[value] = float(StockPriceFile[value])
#2
for value in StockPriceFile:
    value = float(value)

(Sample Of Data)

['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']

where its being written:

Data_AvgFile.write(str(Average)   ',')

What does this mean? and how can i fix it? it works fine when i do it one by one.

(also tell me if you need more data, i dont know if this is sufficient)

CodePudding user response:

for value in StockPriceFile:
    stock_price = float(value.strip('[]'))
    print(stock_price)

strip() will remove the [] characters around the value.

DEMO

CodePudding user response:

As long you have the brackets "[ ]" in you'r string you cant convert it to a a number as that would make it invalid so do letters and most symbols the dot (.) is an exception for float.

>>> print(float('[36800.]'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '[36800.]'
>>> print(float('36800.'))
36800.0
  • Related