布尔运算符如何处理python中的字符串 [英] How does boolean operator work on string in python

查看:31
本文介绍了布尔运算符如何处理python中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

True and "asdf" or "qwer"

结果 => "asdf"

result => "asdf"

False and "asdf" or "qwer"

结果 => "qwer"

result => "qwer"

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

I can't understand how those things work. I thought that boolean operator on string would make type error, but it didn't. Is it something like predefined statement, for instance "a if b else c"?

推荐答案

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

Python and and or operations stop when the answer is determined and return the value of the last object scanned. They do not return True or False. I love this feature and find myself using it all the time.

因为非空字符串算作真

True and "asdf" or absolutely_anything_here_or_following

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

stops calculating when it hits the or because the answer is now determined (one of the or values is true), and returns the last thing it checked ("asdf"). No further operands are even inspected.

另一方面,当

False and "asdf" or absolutely_anything_here

点击,它还不知道答案,所以继续下一个操作数.只要absolute_anything_here是最后一个操作,就确定答案,返回最后扫描的东西.

hits the or, it doesn't know the anwser yet so continues to the next operand. As long as absolutely_anything_here is the last operation, the answer is determined and the last thing scanned is returned.

这篇关于布尔运算符如何处理python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆