我对这些代码有问题.
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","")
Run Code Online (Sandbox Code Playgroud)
我得到'NoneType'对象没有属性'replace'.为什么它会进入第二个条件?
NoneType和之间有区别None.
你需要检查
if type(value) != NoneType:
Run Code Online (Sandbox Code Playgroud)
要么
if value is not None:
Run Code Online (Sandbox Code Playgroud)
但也许以下更直接:
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","")
Run Code Online (Sandbox Code Playgroud)
或者,如果tdinst[1].string 是不是None在大多数情况下,则异常处理速度更快:
try:
value = tdinst[1].string.replace("\n","").replace("\t","")
except TypeError:
value = None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |