8

In python, how to judge whether a variable is bool type,python 3.6 using

    for i in range(len(data)):
        for k in data[i].keys():
            if type(data[i][k]) is types.BooleanType:
                data[i][k] = str(data[i][k])
            row.append(data[i][k])
            #row.append(str(data[i][k]).encode('utf-8'))
        writer.writerow(row)
        row = []

but it errors:

  if type(data[i][k]) is types.BooleanType:

  TypeError: 'str' object is not callable
bin
  • 1,625
  • 3
  • 12
  • 10
  • >>> a=False >>> isinstance(a, bool) True >>> isinstance(a, str) False – CSJ Jan 12 '17 at 09:49
  • Possible duplicate of [Determine the type of a Python object](http://stackoverflow.com/questions/2225038/determine-the-type-of-a-python-object) – Chris_Rands Jan 12 '17 at 09:56
  • 1
    Possible duplicate of [How to compare type of an object in Python?](http://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python) – Saurav Sahu Jan 12 '17 at 10:00

2 Answers2

30

you can check type properly with isinstance()

isinstance(data[i][k], bool)

will return true if data[i][k] is a bool

RichSmith
  • 900
  • 5
  • 11
3
 isinstance(data[i][k], bool) #returns True if boolean

instead of :

if type(data[i][k]) is types.BooleanType:
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44