" == False"之间有区别吗?并且"不是"检查空字符串时?

时间:2016-04-29 10:35:09

标签: python boolean-expression

我已经在stackoverflow的其他地方读过,在Python中检查空字符串的最优雅方法是(例如,让它说出一个名为response的字符串):

if not response:
    # do some stuff 

原因是字符串可以计算为布尔对象。

所以我的问题是,下面的代码是否说同样的话?

if response == False:
    # do some stuff

2 个答案:

答案 0 :(得分:6)

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

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

另一方面,

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

答案 1 :(得分:0)

如前所述,存在差异。

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