python 中的a is not None和 if a:区别

res=requests.get('https://www.zhipin.com/gongsi/_zzz_c101010100_iy100014_t801_s301/',headers=headers)
turn=etree.HTML(res.text).xpath('//div[@class="page"]/a[contains(@ka,"page-next")]/@href')
turn
[]
next_page is not None
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'next_page' is not defined
turn is not None
True
turn
[]
if turn:
    print('sss')
    
turn is not None
True
turn is  None
False


为啥这个是空 写is not None 是对的?这个is not None 什么时候用?

阅读 7.7k
5 个回答
新手上路,请多包涵

因为你写的xpath没有匹配到数据,所以给你返回的是一个空的列表 空列表不是 None 'is not None' 类似 != None
== tests value where is tests to see if they are the same object

因为 [] 是空列表,确实不是 None 啊。
if 的条件如果是 0, 空字符串 '', 空列表 [],布尔值 FalseNone,都会被判断为 False,条件语句不执行。

xx is not None = xx != None
if xx = if xx != None and xx != '' and xx != False and xx != 0 and xx != [] and xx !={} and ...

None 是一个特殊的对象,而一个对象的布尔值是由__bool____len__ 特殊方法决定的。 None更多的时候作为sentinel对象使用,比如判断循环是否执行。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题