Visiting letters, finding a letter, upper case
A loop can visit the characters of a string one by one: for letter in "sun" runs three times, and letter is s, then u, then n. The word in tests whether a piece of text is inside a string: "h" in "school" is True and "z" in "school" is False. The method upper() gives the capital letters: "school".upper() is SCHOOL. Notice that upper() does not change text itself. A string cannot be changed after it is made. If you write text[0] = "S" Python stops with a TypeError. To get a changed version, make a new string and store it, for example with text = text.upper().
1for letter in "sun": 2 print(letter)
s u n
1text = "school" 2print("h" in text) 3print("z" in text) 4print(text.upper()) 5print(text)
True False SCHOOL school
1text = "school" 2text[0] = "S"
TypeError: a string cannot be changed
Plan on paper a program that counts how many times the letter o appears in the word “school”: loop over the letters, compare each with o, and add 1 to a counter. What number does your counter end with?
1for letter in "sun": 2 print(letter)