python中空字符串的布尔值是什么,python-比较字符串和布尔值

I came across a strange behaviour of python comparing a string with True/False.

I thought that python would print in the following:

if "Test" == True:

print("Hello1")

but it does not.

So I wrote some Test cases and I do not understand some of them.

if "Test" == True:

print("Hello1")

if "Test" == False:

print("Hello2")

#This I understand

if bool("Test") == True:

print("Hello3")

#This I understand too

if bool("") == False:

print("Hello4")

if "Test":

print("Hello5")

Output

>> Hello3

>> Hello4

>> Hello5

So I do not understand:

If Hello1 is not printed why is not Hello2 either?

Why does Hello5 get printed, is the cast to bool("Test") made implicit?

解决方案

In the first two comparisons, you are checking whether the string "Test" has the same value as the object True or False. This is a value comparison.

If they have a different type, the comparison will return False. You can see this also when comparing lists, numbers etc.: [1]==1 (false), (1,)==[1] (false).

In the third and fourth comparisons, you are still doing a value comparison, but since both sides are of the same type (boolean), it will compare the values.

Hello5 is printed because it is not the null string "". You can see this by trying "Test" != None, which returns True.

While it is a comparison to None when it comes to most classes(None is Python's null value), Python's standard data types are compared to their "null" value, which are:

The empty string "" for strings,

[] for lists (similary () for tuples, {} for dictionaries),

0 for ints and floats,

just like a boolean comparison. Therefore it is not wrong to think of if expression as an implicit cast to if bool(expression).

What is going on under the hood is the evaluation of the __non-zero__(python2.x) or __bool__(python3.x) method of the class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值