☰ Year plan · Communication Technology

Strings in Python

Week 6 · Unit 1, Lesson 3 Strings and Lists in Python (1) · 3 lessons
3

Visiting letters, finding a letter, upper case

ICT Prep 3 Term 1, Unit 1, Lesson 3: pp. 32–34
GoalVisit the letters of a string with a loop, test membership with in, and use upper.
New words
for loop on a string · visits the characters one by onein · tests whether a piece of text is inside a string; gives True or Falseupper() · gives a new string with capital lettersTrue / False · the two values of a test
Explanation

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().

Python
1for letter in "sun":
2    print(letter)
Output
s
u
n
Worked examples
Python
1text = "school"
2print("h" in text)
3print("z" in text)
4print(text.upper())
5print(text)
Output
True
False
SCHOOL
school
Three tests with in and upper. The original text stays as it was, because upper() makes a new string.
Python
1text = "school"
2text[0] = "S"
Output
TypeError: a string cannot be changed
Changing one character of a string is not allowed. Python stops with a TypeError, so we build a new string instead.
Class activity

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?

Practice
1
What does the loop in the picture show?
Python
1for letter in "sun":
2    print(letter)
2
What is "a" in "planet"?
3
After text = "cat" and text.upper(), what is text?
4
Why does text[0] = "S" fail?