Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuples, checking for a letter in a string

Tags:

python

tuples

I have this code:

prefixes = "JKLMNOPQ" 
suffix = "ack" 

for letter in prefixes: 
    if letter in ("O", "Q"):
        print letter + "u" + suffix
    else:
        print letter + suffix

It works fine but I have problem understanding one thing. I assume that:

if letter in ("O", "Q"):

creates new tuple with 2 letters: O and Q and checks if value letter is present.

What I'm unsure about is why this won't work correctly:

if letter == "O" or "Q":

This code will add "u" to all prefixes and not just those with "O" and "Q".

like image 453
damian Avatar asked Dec 22 '22 10:12

damian


1 Answers

All these do the same thing:

if letter == "O" or letter == "Q":
if letter in ("O", "Q"):
if letter in "OQ":

Your line if letter == "O" or "Q": is evaluated like if (letter == "O") or "Q":, and "Q" evaluates to True, so this expression always returns True.

like image 66
Tim Pietzcker Avatar answered Dec 24 '22 01:12

Tim Pietzcker