是否安全,檢查是否變量myvar
沒有-無值通過簡單:檢查XML ElementTree的節點是無/假
if myvar:
print('Not None detected')
我問這是因爲我有一個變量,並檢查是否該變量不是None
只需if variable:
但該檢查失敗。該變量包含一些數據,但它在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
這實際上是錯誤的。 ''如果myvar:''假設''myvar''爲''None''實際上不會評估爲''True'',因此您的示例將不起作用。不過最好的做法是使用如下形式:''如果myvar不是None:''或''如果myvar是None:'' –
在這裏回答:http://stackoverflow.com/questions/3965104/not-none -python – ka2m
是不是你的檢查失敗,因爲在udh中沒有文本?它可能是一個空的XML節點。 – Midnighter