代码中经常会有变量是否为None的判断,有三种主要的写法:

第一种是`if x is None`;

第二种是 `if not x:`;

第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 。

`if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

使用if not x这种写法的前提是:必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

foo is None 和 foo == None的区别

如果比较相同的对象实例,is总是返回True 而 == 最终取决于 "eq()"

==只要相等,is表明要一样,同一个对象

python判断值是否为空的更多相关文章

  1. python判断字符串是否为空的方法s.strip()=='' if not s.strip():

    python 判断字符串是否为空用什么方法? 复制代码 s=' ' if s.strip()=='':     print 's is null' 或者 if not s.strip():     p ...

  2. token的解码及 判断值不为空的方法

    token 的解码要使用插件:jwt-decode 判断值不为空的方法: function isEmpty(value){ return ( value === undefined || value ...

  3. [Python]判断序列是否为空的正确姿势

    本篇文章起源于StackOverflow上一个热度非常高的问题: 我该如何判断一个Python列表是否为空? @Ray Vega (提问者) 举例说明,现在我得到了如下代码: a = [] 我如何该检 ...

  4. query判断值是否为空,针对前台提交数据的校验

    1.<input type="hidden" id="key" name="key" value="123"> ...

  5. python判断字符串是否为空和null

    1.使用字符串长度判断 len(s==0)则字符串为空 test1 = '' if len(test1) == 0: print('test1为空串') else: print('test非空串,te ...

  6. Python - 判断list是否为空

    Python中判断list是否为空有以下两种方式: 方式一: list_temp = [] if len(list_temp): # 存在值即为真 else: # list_temp是空的 方式二: ...

  7. python 判断字符串是否为空用什么方法?

    s=' ' if s.strip()=='': print 's is null' 或者 if not s.strip(): print 's is null'

  8. python 判断字典是否为空

    my_dict = {} if not bool(my_dict): print("Dictionary is empty")

  9. JS判断输入框值是否为空

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

随机推荐

  1. HDU 3466 Proud Merchants【贪心 + 01背包】

    Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerfu ...

  2. UVA 11396 Claw Decomposition 染色

    原题链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem ...

  3. luogu P1146 硬币翻转

    题目描述 在桌面上有一排硬币,共N枚,每一枚硬币均为正面朝上.现在要把所有的硬币翻转成反面朝上,规则是每次可翻转任意N-1枚硬币(正面向上的被翻转为反面向上,反之亦然).求一个最短的操作序列(将每次翻 ...

  4. JSP(待更新)

    1.概念: 所谓JSP就是在HTML中嵌入大量的java代码而已.

  5. NSPredicate 应用 --数组如何一键去重,如何一行代码筛选,请慢慢看来

    1.去重 NSArray * uniqueVarValueArray= [origArray valueForKeyPath:@"@distinctUnionOfObjects.VarKey ...

  6. Git:fatal: The remote end hung up unexpectedly

    一.配置公共密钥 https://help.github.com/articles/generating-ssh-keys/ 二.设置缓冲值(push文件较大时导致错误) \.git\config [ ...

  7. nodejs处理高并发问题

      做了一个nodejs并发测试,先描述一下环境 数据库mysql,大概两张表,读取第一张表test的数据,拿出来-1,存到第二张testlog表记录一下,用jmeter同事模拟50个请求,结果发现, ...

  8. iframe.contentWindow 属性:关于contentWindow和contentDocument区分

    定义和用法 contentDocument 属性能够以 HTML 对象来返回 iframe 中的文档,可以通过所有标准的 DOM 方法来处理被返回的对象. 语法:frameObject.content ...

  9. ES6里关于类的拓展(二):继承与派生类

    继承与派生类 在ES6之前,实现继承与自定义类型是一个不小的工作.严格意义上的继承需要多个步骤实现 function Rectangle(length, width) { this.length = ...

  10. JPEG编码(一)

    JPEG编码介绍. 转自:http://blog.chinaunix.net/uid-20451980-id-1945156.html JPEG(Joint Photographic Experts ...