1

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Lzypenguin
  • 945
  • 1
  • 7
  • 18

2 Answers2

4

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])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • OMG thank you. This is exactly what I needed. The only problem I am having now is that a few of my numbers are a bit to big and I am getting this result: 8.156e+26 when I should be getting an 11 digit number. – Lzypenguin Dec 20 '20 at 22:13
3

What's happening is that the value of row[1] is a float (you didn't catch this properly in the first if statement - see below). When you evaluate a in b, Python tries to iterate through b to see whether a appears in it. This is why you're getting an error that floats are not iterable.

Now for the if statement - the type function doesn't return a string (though you can force it to by using i.e. str(type(x)). To check whether the type is a float, you want to do:

if type(row[1]) is float:
    # do stuff
    pass
else:
    # do other stuff
    pass

Most likely though, you'd be better off checking if it isn't a string -

if type(row[1]) is not str:
    # do stuff for floats
    pass
else:
    # do other stuff that involves checking if a substring is present
    pass

see also: How to determine a Python variable's type?

devck
  • 331
  • 2
  • 8