问题
I have read elsewhere on stackoverflow that the most elegant way to check for an empty string in Python (e.g. let's say it's a string called response) is to do:
if not response:
# do some stuff
The reason being that strings can evaluate to boolean objects.
So my question is, does the below code say the same thing?
if response == False:
# do some stuff
回答1:
As already mentioned there is a difference.
The not response checks if bool(response) == False or failing that if len(response) == 0 so it is the best choice to check if something is empty, None, 0 or False. See the python documentation on what is considered "Falsy".
The other variant just checks if response == False and this is only the case if and only if response is False. But an empty string is not False!
回答2:
Is there a difference? Yes: one works, and the other doesn't.
if response == False is only true if the actual value of response is False. For an empty string, that is not the case.
if not response, on the other hand, verifies if response is falsey; that is, it is one of the values that Python accepts as false in a boolean context, which includes None, False, the empty string, the empty list, and so on. It is equivalent to if bool(response) == False.
来源:https://stackoverflow.com/questions/36936065/is-there-a-difference-between-false-and-is-not-when-checking-for-an-empty