Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - compare string with boolean

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?
like image 827
JDurstberger Avatar asked Dec 11 '15 08:12

JDurstberger


2 Answers

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.

like image 102
M.T Avatar answered Nov 05 '22 19:11

M.T


In the case of Hello1, Hello2 and Hello5 there is an object comparison and not boolean comparions.

That means that
the string-object "Test" is not the same as object True ("Hello1")
the string object "Test" is not the same as object False("Hello2")
but the string object "Test" is not None ("Hello5")

like image 25
user762353 Avatar answered Nov 05 '22 19:11

user762353