1

I was doing some basic string manipulation and I came across something very interesting and confusing:

str= "HELLO WORLD"
x="LL"

t = x in str
print t

if x in str == True:
    print "TRUE"

When it's run, it currently only prints True on one occasion, on the first print statement. One would think that both would print as logically and almost syntactically they are the same yet one does not. I do not understand the reasoning behind this, especially given how Python is supposed to be intuitive.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
john hon
  • 103
  • 2
  • 2
  • 7

1 Answers1

1

Protect your condition into parentheses:

if (x in str) == True:
    print("TRUE")

Even better: it's redundant to compare to True

if x in str:
    print("TRUE")

That said, it's not beacuse of operator precedence:

x in (str == True)

is invalid (cannot iterate on a boolean)

x in str == True

is valid but returns False. I must admit I'm still puzzled about that...

EDIT: just saw the duplicate and now I get it. Lesson #1: always protect your expressions with parentheses when you have a doubt.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219