zoukankan      html  css  js  c++  java
  • python-s and s.strip()

    s and s.strip()“ 这个表达式的值。Python语法是这么运行的:

    如果s is None,那么s会被判断为False。而False不管和什么做and,结果都是False,所以不需要看and后面的表达式,直接返回s(注意不是返回False)。
    如果s is not None,那么s会被判断为True,而True不管和什么and都返回后一项。于是就返回了s.strip()。

    所以s.strip() 不能单独使用,语法是有问题的
    >>> def not_empty(s):
    	return s.strip()
    
    >>> list(filter(not_empty,['A','','B','C',None,' ']))
    Traceback (most recent call last):
      File "<pyshell#17>", line 1, in <module>
        list(filter(not_empty,['A','','B','C',None,' ']))
      File "<pyshell#16>", line 2, in not_empty
        return s.strip()
    AttributeError: 'NoneType' object has no attribute 'strip'
    

     正确用法:

    >>> def not_empty(s):
    	return s and s.strip()
    
    >>> list(filter(not_empty,['A','','B','C',None,' ']))
    ['A', 'B', 'C']
    
  • 相关阅读:
    内置函数二
    通信的几个程序
    TCP协议和UDP协议
    异常处理
    logging模块
    网络编程一些概念
    hashlib
    序列化模块
    time,sys,os模块
    random模块
  • 原文地址:https://www.cnblogs.com/sincoolvip/p/7324635.html
Copyright © 2011-2022 走看看