I have a list of strings in the form like
a = ['str','5','','4.1']
I want to convert all numbers in the list to float, but leave the rest unchanged, like this
a = ['str',5,'',4.1]
I tried
map(float,a)
but apparently it gave me an error because some string cannot be converted to float. I also tried
a[:] = [float(x) for x in a if x.isdigit()]
but it only gives me
[5]
so the float number and all other strings are lost. What should I do to keep the string and number at the same time?
>>> a = ['str','5','','4.1']
>>> a2 = []
>>> for s in a:
... try:
... a2.append(float(s))
... except ValueError:
... a2.append(s)
>>> a2
['str', 5.0, '', 4.0999999999999996]
If you're doing decimal math, you may want to look at the decimal module:
>>> import decimal
>>> for s in a:
... try:
... a2.append(decimal.Decimal(s))
... except decimal.InvalidOperation:
... a2.append(s)
>>> a2
['str', Decimal('5'), '', Decimal('4.1')]
for i, x in enumerate(a):
try:
a[i] = float(x)
except ValueError:
pass
This assumes you want to change a
in place, for creating a new list you can use the following:
new_a = []
for x in a:
try:
new_a.append(float(x))
except ValueError:
new_a.append(x)
This try/except approach is standard EAFP and will be more efficient and less error prone than checking to see if each string is a valid float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With