Is there a difference between “== False” and “is not” when checking for an empty string?

一世执手 提交于 2019-11-27 08:15:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!