检查空字符串时,"== False" 和 "is not" 有区别吗?

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

我在 Whosebug 的其他地方读到,检查 Python 中的空字符串(例如,假设它是一个名为 response 的字符串)的最优雅的方法是:

if not response:
    # do some stuff 

原因是字符串可以评估为布尔对象。

所以我的问题是,下面的代码是否表达了同样的意思?

if response == False:
    # do some stuff

有区别吗?是的:一个有效,另一个无效。

if response == False 仅当 response 的实际值为 False 时才为真。对于空字符串,情况并非如此。

另一方面,

if not response 验证 response 是否为假;也就是说,它是 Python 在布尔上下文中接受为 false 的值之一,其中包括 None、False、空字符串、空列表等。相当于if bool(response) == False.

如前所述,两者之间存在差异。

not response 检查是否 bool(response) == False 或如果 len(response) == 0 失败所以它是检查是否为空的最佳选择,None0False。参见 the python documentation on what is considered "Falsy"

另一个变体只检查是否 response == False 并且只有 当且仅当 response is False 时才会出现这种情况。但是一个空字符串 is not False!