Example 2: Given two strings, find all characters appearing in both.

We are given two strings and want to print the letters appearing in both strings. We use a for loop to iterate over one of the strings, string1, and compare every letter in string1 with letters in string2.

Compared to other languages, Python makes this easy and the following code is quite intuitive:

# 02Loops example_02 Strings.py
string1  = 'house'
string2 = 'our'

print "letters in both", string1, "and", string2, "are"

for letter in string1:  #Use each letter in string1 to test if it is in string2
    if letter in string2:
        print(letter) 	#If a letter is also in string2, print it out

It may be helpful to students to run the code in PythonTutor to see the value of letter as the for loop executes.