What's a simple way to convert stings into numerics:
from:
['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']
to:
[3.65e+03, 1.14e+04, 1.35e+04, 1.46e+04]
Thanks.
First off, I hope you are aware of the limitations in representing the floating point accurately in our current architectures.
The simple way for conversion is simply this.
>>> s = ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']
>>> map(float,s)
>>> [3650.0, 11400.0, 13500.0, 14600.0]
But float rounds them off to the nearest value and it's representation does not matter as long as values are same. Sometimes, those values can have near-equal representation with same value (almost) for e.g.
>>> s = ['3.65e+93', '1.14e+04', '1.35e+04', '1.46e+04']
>>> map(float,s)
[3.6500000000000001e+93, 11400.0, 13500.0, 14600.0]
Update - Please see John Machin's comment for this behavior/repr.
But if you want exact representation, for e.g. if you are dealing calculations involving money, then you may want to use the Decimal type instead of float, which for all purposes can behave in the same way as your float.
>>> from decimal import Decimal
>>> map(Decimal,s)
[Decimal('3.65E+93'), Decimal('1.14E+4'), Decimal('1.35E+4'), Decimal('1.46E+4')]
float() ALWAYS rounds to the nearest float value, if necessary. "As you saw"?? There is NO ROUNDOFF involved in your first map() output. In your second, 3.6500000000000001e+93 is merely an artifact of your use of a pre-2.7 Python, where repr() always used 17 decimal digits of precision. Python 2.7 produces 3.65e+93. In ANY Python, 3.6500000000000001e+93 == 3.65e+93 is true. Very shaky grounds for introducing decimal which has its own limited precision.getcontext().prec =n isn't it?map(float, your_list)
or
[float(x) for x in your_list]
Update For an explanation of why an unqualified recommendation to "use decimal" is not a good idea, see my answer to another question.
if clause when required. BTW, did you intend to link to this answer?numbers = [eval(s) for s in ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']]
eval's a bit of a hack, but it's pretty well guaranteed to work. (specific float is also a good approach.)
eval() is a huge risk as it allows arbitrary code to be executed. Even discounting this security risk, why would you want to use eval() over the in-built float() function which was designed specifically for this purpose?