You could cut down on code slightly by just writing
if variable and variable.upper() == "X":
#Do something
If the variable is none or empty, then it's equivalent to False.
Answer from obmarg on Stack OverflowYou could cut down on code slightly by just writing
if variable and variable.upper() == "X":
#Do something
If the variable is none or empty, then it's equivalent to False.
if variable and variable.upper() == 'X'
is a little less wordy. It will also treat None and the empty string in the same way if that is something you want
Edit: Note that this does have different semantics to the expression you posted in the way it handles empty strings... i.e. in your expression the rhs of the and would get evaluated if variable is the empty string, but in this expression it would not as the empty string evaluates to False
I recently came across a problem in a textbook where these 2 were interchangeable. So whatโs the difference between these 2 and when to use which? Thanks!
Edit for context:
would like to clarify the use of None in this question to initialize the while loop, how does it initialize the loop?
start = None
while start != โโ: start = int(input(โStart: โ) . . .
Videos
Checking if a string has characters in it by checking len(str(result)) is definitely not pythonic (see http://www.python.org/dev/peps/pep-0008/).
result = foo() # foo will return None if failure
if result:
# deal with result.
pass
None and '' coerce to the boolean False.
If you are really asking why str(None) does return 'None', then I believe it is because it is necessary for three-valued logic. True, False and None can be used together to determine if a logical expression is True, False or cannot be decided. The identity function is the easiest for representation.
True -> 'True'
False -> 'False'
None -> 'None'
The following would be really weird if str(None) was '':
>>> or_statement = lambda a, b: "%s or %s = %s" % (a, b, a or b)
>>> or_statement(True, False)
'True or False = True'
>>> or_statement(True, None)
'True or None = True'
>>> or_statement(None, None)
'None or None = None'
Now, if you really want for an authoritative answer, ask Guido.
If you really want to have str(None) give you '' please read this other question: Python: most idiomatic way to convert None to empty string?
Basically, because an empty string isn't a representation of None. None is a special value that is distinct from an empty string or anything else. As described in the docs, str is supposed to
Return a string containing a nicely printable representation of an object.
Basically, str is supposed to return something printable and human-readable. An empty string would not be a readable representation of None.