python一切皆对象。None是python的一个内建值,它确切的含义是“这里什么也没有”。简而言之,python把None、0、空字符串''、空容器如空列表[]、空元组()、空字典{}等一系列代表空和无的对象转换成False,其它数值、非空字符串和非空对象都转成True。

1.None

>>> a = None
>>> a
>>> type(a)
<class 'NoneType'>
>>> if not a:
	print(1)

	
1
>>> if a is None:
	print(1)

	
1
>>> 

2、''

>>> b = ''
>>> b
''
>>> type(b)
<class 'str'>
>>> if not b:
	print(1)

	
1
>>> if b is '':
	print (1)

	
1
>>> if '' == b:
	print(1)

	
1
>>> # ''并不是None
>>> if b is None:
	print(1)

	
>>> 
>>> 

3、' ',为空格符

>>> c = ' '
>>> c
' '
>>> type(c)
<class 'str'>
>>> if not c:
	print(1)

	
>>> 
>>> ord(c)
32
>>> 

4、0

>>> d = 0
>>> d
0
>>> type(d)
<class 'int'>
>>> if not d:
	print(1)

	
1
>>>

5、空列表[]

>>> lst = list()
>>> lst
[]
>>> type(lst)
<class 'list'>

#判断列表是否为空: if not list或if list或if 0 == len(list)

>>> if not lst:
	print(1)

	
1
>>> if lst:
	print(1)

	
>>> if 0 == len(lst):
	print(1)

	
1
>>> 

注意,内容为None的列表不代表它是个空列表,它其实已经是个有长度的列表了。

>>> lst1 = [None] * 3
>>> lst1
[None, None, None]
>>> if not lst1:
	print(1)

	
>>> if lst1:
	print(1)

	
1
>>> if 0 == len(lst1):
	print(1)

	
>>> 

6、空元组(),与列表一样

>>> tup = tuple()
>>> tup
()
>>> type(tup)
<class 'tuple'>
>>> if not tup:
	print(1)

	
1
>>> if tup:
	print(1)

	
>>> if 0 == len(tup):
	print(1)

	
1
>>> 
>>> tup1 = (None,)
>>> tup1
(None,)
>>> type(tup1)
<class 'tuple'>
>>> if not tup1:
	print(1)

	
>>> if tup1:
	print(1)

	
1
>>> if 0 == len(tup1):
	print(1)

	
>>> len(tup1)
1
>>> 

7、字典,与列表一样

>>> dic = dict()
>>> dic
{}
>>> type(dic)
<class 'dict'>
>>> if not dic:
	print(1)

	
1
>>> if dic:
	print(1)

	
>>> if 0 == len(dic):
	print(1)

	
1
>>> 
>>> dic1 = {None}
>>> dic1
{None}
>>> type(dic1)
<class 'set'>
>>> dic1 = {None:None}
>>> dic1
{None: None}
>>> type(dic1)
<class 'dict'>
>>> if not dic1:
	print(1)

	
>>> if dic1:
	print(1)

	
1
>>> if 0 == len(dic1):
	print(1)

	
>>> len(dic1)
1
>>> 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐