Search code examples
pythonpython-3.xstringfloating-pointrtti

Python How to check if an item in a list is a float, and if so, change it to a string?


I am iterating through an excel sheet. Some of my info in some columns is coming across as a float. I have done everything I can through excel to try and make it not a float and it wont fix it.

I am using xlrd to read data.

for i in range(ws.nrows):
    row = ws.row_values(i)
    if type(row[1]) == 'float':
        row[1] = str(row[1])
    if ',' in row[1]:
        DO STUFF

I keep getting this error:

if ',' in row[1]:
TypeError: argument of type 'float' is not iterable

For some reason this is not working. I can even print the type as I am iterating through the list, and it will say class 'float' but it never seems to go into the if type loop.


Solution

  • type returns the actual float class, not the string 'float'. The easiest way to check for the type would be to use the isinstance builtin function:

    if isinstance(row[1], float):
        row[1] = str(row[1])