Search code examples
pythonlistfloating-pointtype-conversionstrip

How to handle an exception while converting a literal present in a list to float?


A=[None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0']
B=[]
for elem in A:
    if elem is not None:
        B.append(float(elem.strip("''")))
    else:
         B.append(elem )
print B

I have a list which has values shown above. When I am trying to add to an excel sheet using pandas, it is being added as text rather than float or int. I want to remove quotation marks so that it won't be seen as text in excel sheet, I know it can be done using split, and if I try to convert all of these to float, it throws an exception for this '0(1:1)' element saying that invalid literal for for float.How do I handle this?


Solution

  • The simpler solution is to wrap the for body in a try-except and append None or the original value (elem) if it fails for a particular iteration:

    A = [None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0']
    
    B = []
    
    for elem in A:
        try:
            B.append(float(elem))
        except (ValueError, TypeError) as error:
            B.append(elem)
    
            # Or, if you don't want to preserve the non-numeric values:
    
            # B.append(None)
    
    print(B)
    

    A ValueError will be thrown when elem can't be parsed as float, while TypeError will be thrown when elem is None.

    Like that you don't need to check if elem is None using and if and both exceptions can be handled consistently (assuming that's what you want).

    Note the .strip("''") is not needed as it is actually not doing anything. According to the docs, strip() will...:

    Return a copy of the string with the leading and trailing characters removed.

    That is, it will try to remove '' from the start and the end of your values, but none of your values start or end with two single quotes. Actually, any of them contain quotes at all, those around them are just the way to represent a string, but are not part of their value.

    Also, float() will automatically take care of converting a string representation of a number ('1') to Float.