Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
Answer from Andrew Clark on Stack OverflowEmpty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
From PEP 8, in the “Programming Recommendations” section:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So you should use:
if not some_string:
or:
if some_string:
Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
You could just compare your string to the empty string:
if variable != "":
etc.
But you can abbreviate that as follows:
if variable:
etc.
Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.
The "Pythonic" way to check if a string is empty is:
import random
variable = random.choice(l)
if variable:
# got a non-empty string
else:
# got an empty string
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: “) . . .
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.
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