Wondering if if not foo is None is the same as if foo? Using Python 2.7 and foo is a string.
Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.
Using len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as empty string even its non zero.
Method #1 : Using all() + not operator + values() The not operator is used to inverse the result to check for any of None value.
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
For empty strings both are different:
foo = ''
if foo:
    print 'if foo is True'
will not print anything because it is empty and therefore considered False but:
if foo is not None: 
    print 'if not foo is None is True'
will print because foo is not None!
I Changed it according to PEP8. if foo is not None is equivalent to your if not foo is None but more readable and therefore recommended by PEP8.
if a is None:
    pass
The if will only be True if a = None was explicitly set.
On the other hand:
if a:
    pass
has several ways of evaluating when it is True:
Python tries to call a.__bool__ and if this is implemented then the returned value is used.
None, False, 0.0, 0 will evaluate to False because their __bool__ method returns False.If a.__bool__ is not implemented then it checks what a.__len__.__bool__ returns.
'', [], set(), dict(), etc. will evaluate to False because their __len__ method returns 0. Which is False because bool(0) is False.If even a.__len__ is not implemented then if just returns True.
True.See also: truth-value-testing in thy python documentation.
No, not the same when foo is an empty string.
In [1]: foo = ''
In [2]: if foo:
   ...:     print 1
   ...:
In [3]: if foo is None:
   ...:     print 2
   ...:
In [4]: if not foo is None:
   ...:     print 3
   ...:
3
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With