Search code examples
pythonpython-3.xtypestype-conversiontry-except

Trying to convert to numbers with try except


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...

  1. How do I skip over the None item? Do I have to use an if item == None: pass statement, or is there a better way?
  2. Why is the type conversion not working even if I change None to "None"?

Solution

  • 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)