【发布时间】:2014-06-29 11:20:45
【问题描述】:
简单地检查变量myvar是否具有非无值是否安全:
if myvar:
print('Not None detected')
我问这个是因为我有一个变量,并且正在通过简单的if variable: 检查变量是否不是None,但检查失败了。该变量包含一些数据,但在 if 检查中评估为 False。
完整代码:
from xml.etree import ElementTree as ElementTree
root = ElementTree.fromstring('Some xml string')
parameters = root.find('Some Tag')
udh = parameters.find('UDH')
if udh and udh.text: # In this line the check is failing, though the udh variable has value: <Element 'UDH' at 0x7ff614337208>
udh = udh.text
# Other code
else:
print('No UDH!') # Getting this output
【问题讨论】:
-
这实际上是错误的。
if myvar:假设myvar是None实际上不会评估为True,因此您的样本将无法工作。但是,最好使用以下形式:if myvar is not None:或if myvar is None: -
您的检查不是因为 udh 中没有文本而失败吗?它可能是一个空的 XML 节点。
-
@Midnighter 我确定我的 udh 节点中有文本。
-
@Midnighter 但它没有任何子节点。这是否有可能被评估为 False?
标签: python