I'm trying to convert the items in a list of multiple types to floats, so that
L = ["29.3", "tea", "1", None, 3.14]
would become
D = [29.3, "tea", 1, None, 3.14]
My attempt is as follows:
L = ["29.3", "tea", "1", None, 3.14]
D = []
for item in L:
try:
float(item)
D.append(item)
except ValueError:
D.append(item)
print(D)
This throws up a
line 5, in <module> float(item) TypeError: float() argument must be a string or a number, not 'NoneType'` error.
If I change the None
item to a string as in "None"
, it generates a list D
identical to L
. So...
None
item? Do I have to use an if item == None: pass
statement, or is there a better way?None
to "None"
?try-except
is for catching exceptions. In this scenario, you only account for one exception, ValueError
but not TypeError
. In order to catch type error, just put one more except
block below try
. In your case, it would be like this:
L = ["29.3", "tea", "1", None, 3.14]
D = []
for item in L:
try:
float(item)
D.append(float(item))
except TypeError:
# do something with None here
except ValueError:
D.append(item)
print(D)
Given that you want to catch multiple exceptions in a single except
block, use a tuple of exceptions:
L = ["29.3", "tea", "1", None, 3.14]
D = []
for item in L:
try:
float(item)
D.append(float(item))
except (ValueError, TypeError):
D.append(item)
print(D)