I just stumbled across this and I couldn't find a sufficient answer:
x = ""
Why then is:
x == True
False
x == False
False
x != True
True
x != False
True
Am I supposed to conclude that x
is neither True
nor False
?
I just stumbled across this and I couldn't find a sufficient answer:
x = ""
Why then is:
x == True
False
x == False
False
x != True
True
x != False
True
Am I supposed to conclude that x
is neither True
nor False
?
to check if x is True of False:
bool("")
> False
bool("x")
> True
for details on the semantics of is
and ==
see this question
Am I supposed to conclude that x is neither True nor False?
That's right. x
is neither True
nor False
, it is ""
. The differences start with the type:
>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool
Python is a highly object oriented language. Hence, strings are objects. The nice thing with python is that they can have a boolean representation for if x: print("yes")
, e. g.. For strings this representation is len(x)!=0
.
In python '==' tests for equality. The empty string is not equal to True, so the result of your comparison is False.
You can determine the 'truthiness' of the empty string by passing it to the bool function:
>>> x = ''
>>> bool(x)
False
In a Boolean context, null / empty strings are false (Falsy). If you use
testString = ""
if not testString:
print("NULL String")
else:
print(testString)
As snakecharmerb said, if you pass the string to the bool() function it will return True or False based
>>> testString = ""
>>> bool(testString)
False
>>> testString = "Not an empty string"
>>> bool(testString)
True
See this doc on Truth Value Testing to learn more about this:
Python 2:
https://docs.python.org/2/library/stdtypes.html#truth-value-testing
Python 3:
https://docs.python.org/3/library/stdtypes.html#truth-value-testing
x represents an empty string literal object. By itself it is not a boolean type value, but as the other answers suggest a "cast" to boolean is possible. When used in an if statement condition check expression, the expression will evaluate to "False-y" due to the string being empty.
However your comparison examples compare the object x to the singleton objects "True" and "False", which falls back to a "is" comparison. Since the objects are different, the compare evaluates to False for when checking equality.
(For details look at Returning NotImplemented from __eq__ )
© 2022 - 2024 — McMap. All rights reserved.
x
isn't equal to eitherTrue
orFalse
. Why did you think it would be? Have you been confused somehow by docs.python.org/2/library/stdtypes.html#truth-value-testing? It will still evaluate false-y in a boolean context:if x:
,bool(x)
, etc.. – Broganbool(x) == False
. Username checks out, though. – Hairpinx=0
. And then do the same thing withx=1
. – Warfield