6

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Dr.Tautology
  • 416
  • 1
  • 8
  • 19
  • What?! You are to conclude that `x` isn't *equal to* either `True` or `False`. Why did you think it would be? Have you been confused somehow by https://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.. – jonrsharpe Mar 15 '16 at 14:00
  • 1
    Dr. Tautology, I think what you meant to test was if `bool(x) == False`. Username checks out, though. – pholtz Mar 15 '16 at 14:08
  • Now see what happens with your tests if you set `x=0`. And then do the same thing with `x=1`. – PM 2Ring Mar 15 '16 at 14:29
  • 2
    @PM2Ring Ask one bad question on stackoverflow and it ruins your day.FML – Dr.Tautology Mar 15 '16 at 15:07
  • Hey, it's not _that_ bad. Sure, it's got a net zero score, but you won a few rep points from it, and you got some good answers. But yes, this is fairly basic info that isn't that hard to find in the official documentation. – PM 2Ring Mar 15 '16 at 23:33

4 Answers4

6

to check if x is True of False:

bool("")
> False

bool("x")
> True

for details on the semantics of is and == see this question

Community
  • 1
  • 1
scytale
  • 12,346
  • 3
  • 32
  • 46
4

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.

Chickenmarkus
  • 1,131
  • 11
  • 25
2

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
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
1

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

ode2k
  • 2,653
  • 13
  • 20