简体   繁体   English

如何将str转换为浮点数?

[英]How to convert str to a float?

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 12, in <module>
    StockPriceFile = float(value.strip(''))
ValueError: could not convert string to float: 

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)
#3
StockPriceFile[0] = StockPriceFile[0].strip('[]')
for value in StockPriceFile:
    StockPriceFile = float(value.strip(''))

(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) (也告诉我您是否需要更多数据,我不知道这是否足够)

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

strip() will remove the [] characters around the value. strip()将删除值周围的[]字符。

DEMO演示

As long you have the brackets "[ ]" in you'r string you cant convert it to aa 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
l = ['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
[float(f.strip('[]')) for f in l]

Output: Output:

[36800.0,
 36816.666666666664,
 36816.666666666664,
 36833.333333333336,
 36866.666666666664]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM