布尔运算符如何处理python中的字符串

jin*_*wan 3 python

True and "asdf" or "qwer"
Run Code Online (Sandbox Code Playgroud)

结果 => "asdf"

False and "asdf" or "qwer"
Run Code Online (Sandbox Code Playgroud)

结果 => "qwer"

我无法理解这些东西是如何运作的。我认为字符串上的布尔运算符会导致类型错误,但事实并非如此。它是否类似于预定义语句,例如“a if b else c”?

tde*_*ney 5

当确定答案并返回最后一个扫描对象的值时,Python操作停止。它们不返回TrueFalse。我喜欢这个功能,并且发现自己一直在使用它。

由于非空字符串算作 True

True and "asdf" or absolutely_anything_here_or_following
Run Code Online (Sandbox Code Playgroud)

当它遇到or时停止计算,因为现在确定了答案(or值之一为真),并返回它检查的最后一项(“asdf”)。甚至不检查进一步的操作数。

另一方面,当

False and "asdf" or absolutely_anything_here
Run Code Online (Sandbox Code Playgroud)

命中or,它还不知道 anwser 所以继续下一个操作数。只要absolute_anything_here是最后一个操作,就确定答案并返回最后扫描的东西。