0

Say i have 2 strings that both contain the letter B, How would i check to confirm that both strings contain the same letter?

I tried doing:

myString1 = 'JILL'
myString2 = 'BOB'
if 'B' or 'K' in myString1 and myString2:
    print('both strings contain the same letter')

The print statement is still reached even though myString1 does not contain the letters K or B.

I would think that the "and" operator would be like saying both variables need to contain the same letter for the print statement to be reached but this is not the case, Instead the print statement is always reached regardless of weather or not both strings contain the same letter.

Skilo Skilo
  • 526
  • 4
  • 11
  • 23

1 Answers1

0

You can use any with as many characters as you want to check:

to_check = ('B', 'K')
if any(c in myString1 and c in myString2 for c in to_check):

Your code fails as if 'B' is always True, you are checking if B is not a falsey value which for all but an empty string would be True if you were to write out it out explicitly without using any then it would be:

if 'B' in myString1 and B' in myString2 or 'K' in myString1 and 'K' in myString2: 
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321