bin
bin

Reputation: 1925

python how to judge whether a variable is boolean type

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

Upvotes: 8

Views: 30556

Answers (2)

Taufiq Rahman
Taufiq Rahman

Reputation: 5704

 isinstance(data[i][k], bool) #returns True if boolean

instead of :

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

Upvotes: 3

RichSmith
RichSmith

Reputation: 940

you can check type properly with isinstance()

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

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

Upvotes: 32

Related Questions