Home > OS >  Converting a string to an integer or float
Converting a string to an integer or float

Time:12-01

I have the following list:

[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06
  1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]

When I return its type, I get:

<class 'str'>

Is the reason for that the scientific notation used for instance (i.e. e-04)?

In this case, how can I convert the above list to an integer or float?

Thanks.

CodePudding user response:

What you posted must be part of a string literal:

s = '[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06 1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]'

In which case

list(map(float, s.lstrip('[').rstrip(']').split()))

evaluates to

[1.01782362e-05, 0.000193798303, 7.96163586e-05, 5.08812627e-06, 1.39600188e-05, 0.000394912873, 0.000233748418, 1.22856018e-05]

CodePudding user response:

We can use python ast (Abstract Syntax Tree) to process it efficiently

import ast
x = '[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06 1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]'
x = ast.literal_eval(x.replace(" ",","))
print(x)
  • Related