python-比较字符串和布尔值 [英] python - compare string with boolean

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

问题描述

我遇到了python将字符串与True / False进行比较的奇怪行为。

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

我认为python将在以下内容中打印:

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")

输出

>> Hello3
>> Hello4
>> Hello5

所以我不明白:


  • 如果没有打印Hello1,为什么还没有打印Hello2?

  • 为什么打印Hello5,是否将强制转换为bool( Test)的内容?

推荐答案

在前两个比较中,您正在检查字符串 测试 与对象 True False 具有相同的值。这是一个值比较。

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.

如果它们的类型不同,则比较将返回 False 。在比较列表,数字等时,您也可以看到以下内容: [1] == 1 (false),(1,)== [1 ] (false)。

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 因为不是空字符串 。您可以通过尝试 Test!= None 看到此结果,它返回 True

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

虽然与大多数课程的 None 相比( None 是Python的null值),将Python的标准数据类型与其 null值进行比较,即:

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:


  • 空字符串 表示字符串,

  • [] 表示列表(对于元组,类似性(),对于字典, {} ),

  • 0 用于整数和浮点数,

  • The empty string "" for strings,
  • [] for lists (similary () for tuples, {} for dictionaries),
  • 0 for ints and floats,

就像布尔比较一样。因此,将 if expression 视为对 if bool(expression)的隐式转换是正确的。

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

内部进行的是对 __非零__ (python2.x)或 __ bool __ (python3.x)类的方法。

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

这篇关于python-比较字符串和布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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