Vindhya G
Vindhya G

Reputation: 1369

Not matching is not NoneType condition in Python

I m having problem with these piece of code.

if tdinst[0].string in features:
       nameval=tdinst[0].string
       value=tdinst[1].string
       print type(value)
       if type(value) is not None:
               print"it should not come here"
              value=value.replace("\n","")
              value=value.replace("\t","")

I m getting 'NoneType' object has no attribute 'replace'.Why is it going inside second if condition?

Upvotes: 2

Views: 706

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

There's a difference between NoneType and None.

You need to be checking

if type(value) != NoneType:

or

if value is not None:

but perhaps the following is more straightforward:

if tdinst[0].string in features:
    nameval = tdinst[0].string
    value = tdinst[1].string
    if value: # this is also False if value == "" (no need to replace anything)
        value = value.replace("\n","").replace("\t","")

or, if tdinst[1].string is not None in the majority of cases, then exception handling is faster:

try:
    value = tdinst[1].string.replace("\n","").replace("\t","")
except TypeError:
    value = None

Upvotes: 7

Rohit Jain
Rohit Jain

Reputation: 213391

There is no such type as None. You probably meant NoneType:

if type(value) is not NoneType:

But why are you testing against type? Just check for value:

if value is not None:

Upvotes: 4

Related Questions