Back

The 'in' operator and strings

The operator 'in' is Boolean. It is True if one string is insid another, and False if one string is not inside another.

Q1. Write a program that checks the following are correct:

'o' in 'mouse returns True.
'x' in 'rat' returns False.
'pen' in 'open room' returns True.
'Pencil' in 'open room' returns False.

Q2. We can combine the Boolean operator 'in' with the Boolean operator 'not' to create a useful tool. Using the code written for Q1 above, modify it using the 'not' operator to test that these are correct:

'o' not in 'mouse returns False.
'x' not in 'rat' returns True.
'pen'not in 'open room' returns False.
'Pencil' not in 'open room' returns True.

Q3. Enter the following code and get it working: 

def common(firstWord, secondWord):
for letter in firstWord:
    if letter in secondWord:
        print(letter)

common('alphabet', 'tablet')
print('\n\n')
common('mississippi', 'miss')

Q4. The above program takes each letter in turn and checks to see if it is in the second word. If it is, it prints it out. A problem with this program is that if a letter has already been printed out, it will still print the letter again if it occurs.

Modify the above program so that if a letter in the first word appears in the second word, but it has already been printed out, it isn't printed again.

Back