python【变量】【字符串】空值判断

快速过目:
if X:…do something…
if X is None:
if not X:
if not X is None:
if s.strip()==”:

一目了然看代码:

#判断字符串是否为空,注意不是s==''
s=' '
if s.strip()=='':
    print 's is null'
#或者
if not s.strip():
    print 's is null'

#判断变量是否为空,直接用变量为条件
p = ''   #这里仅以空字符串为例,其他空值同样适用
if p:
   print 'p is not empty'
else:
   print 'p is none'
#其他三种写法:
if X is None:
if not X:
if not X is None:

详细解释

python语言与其他语言不同,没有NULL类型,空用none来表示,
但同时需要注意,none是有数据类型的,type为‘Nonetype’
因此python中判断对象为不为空时需要注意对象类型
example:
type:str
判断语句:if val.strip() == ‘’:

很容易犯的错误:

if a is None:
    do something.
else:
    do the other thing.

这样写看起来不错,但实际上会有问题。一般来讲,Python中会把下面几种情况当做空值来处理:

  • None
  • False
  • 0,0.0,0L
  • ”,(),[],{}

其中None的特殊之处在于,它既不是数值0,也不是某个数据结构的空值,它本身就是一个空值对象。它的类型是NoneType,它遵循单例模式,也就是说,在同一命名空间下的所有None其实质上都是同一个空值对象。

>>> id(None)
1795884240
>>> None == 0
False
>>> None == ''
False
>>> a = None
>>> id(a)
1795884240
>>> a == None
True

上面的判断显然不符合我们的期望:只有当a被显示赋值为None的情况下,a==None才为True

那么,对于Python中更为广义的None值判断,我们应该怎么做呢?

>>> a = ''    #这里仅以空字符串为例,其他空值同样适用
>>> if a:
...        print 'a is not empty'
...    else:
...        print 'a is a empty string'
'a is a empty string.' 

可以看出,if a的判断方式得出了我们想要的结果,那么if a的判断方式究竟是一个怎样的过程呢?
if a会首先去调用a的__nonzero__()去判断a是否为空,并返回True/False,若一个对象没有定义__nonzero__(),就去调用它的__len__()来进行判断(这里返回值为0代表空),若某一对象没有定义以上两种方法,则if a的结果永远为True
接下来验证一下上面的说法:

>>>class A(object):
...        def __nonzero__(self):
...            print 'running on the __nonzero__'
...            return True
>>>class B(object):
...        def __len__(self):
...            print 'running on the __len__'
...            return False
>>> a, b = A(), B()
>>>if a:
...        print 'Yep'
...    else:
...        print 'Nop'
running on the __nonzero__
Yep
>>>if b:
...        print 'Yep'
...    else:
...        print 'Nop'
running on the __len__
Nop

变量判空三种主要的写法有:

第一种:if X is None;

第二种:if not X;

当X为None,  False, 空字符串””, 0, 空列表[], 空字典{}, 空元组()这些时,not X为真,即无法分辨出他们之间的不同。

第三种:if not X is None;

 在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。

在命令if not 1中,1便会转换为bool类型的True。not是逻辑运算符非,not 1则恒为False。因此if语句if not 1之下的语句,永远不会执行。

对比:foo is None 和 foo == None

示例:

>>> class Foo(object):
       def __eq__(self, other):
           return True

>>> f = Foo()
>>> f == None
True
>>> f is None
False

python中的not具体表示是什么

在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法:
(1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。比如:
a = False
if not a: (这里因为a是False,所以not a就是True)
print “hello”
这里就能够输出结果hello
(2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,比如:
a = 5
b = [1, 2, 3]
if a not in b:
print “hello”
这里也能够输出结果hello
not x 意思相当于 if x is false, then True, else False

项目中遇到一个实际的问题:

数据库中看:数据值为null
python读入:type类型结果为str
初步处理结果:如上所示的空字符串方法以及判断none方法各种方法各种试,一直不成功(天真的一直以为null代表这个是空字符串的意思)
后续处理结果:其实就是个‘null’的字符串(不能想太多)
判断语句:if val == ‘null’:

其他判空方法:

# -*- coding: UTF-8 -*-

def main():
    list_1 = []  # 定义一个空链表
    if len(list_1) == 0:  # 如果此链表的长度为0则为空
        print('None')
    list_2 = [1]
    if len(list_2) > 0:  # 如果长度大于1则不为空
        print('not none')

main()

更多资源:

http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none

http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none

作者:

喜欢围棋和编程。

 
发布于 分类 编程标签

发表评论

邮箱地址不会被公开。