2

我对这些代码有问题。

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","")

我得到'NoneType'对象没有属性'replace'。为什么它会进入第二个if条件?

4

2 回答 2

7

NoneType和之间有区别None

你需要检查

if type(value) != NoneType:

或者

if value is not None:

但也许以下内容更简单:

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","")

或者,如果tdinst[1].string 不是None大多数情况下,那么异常处理会更快:

try:
    value = tdinst[1].string.replace("\n","").replace("\t","")
except TypeError:
    value = None
于 2013-02-13T17:36:42.973 回答
4

没有这样的类型None。您可能的意思是NoneType

if type(value) is not NoneType:

但是你为什么要测试type呢?只需检查value

if value is not None:
于 2013-02-13T17:36:53.843 回答