Course outline · 0% complete

0/27 lessons0%

Course overview →

Looping over text

lesson 5-4 · ~11 min · 18/27

Strings are sequences too

A lot of everyday engineering is examining text one character at a time: a password checker counting digits, a form validator hunting for illegal characters, a word game scoring letters. Python makes this direct, because a for loop can walk any sequence — and a string is a sequence of its characters.

for letter in "code":
    print(letter)

This runs the body four times, with letter holding "c", then "o", then "d", then "e". It is the same for loop from lesson 5-1; the only change is looping over a string's characters instead of range's numbers.

One more built-in instruction earns its keep here: len(...) takes a string and gives back how many characters it contains, as a number. len("banana") is 6. (It works on other sequences too, as you will see in the next course.)

Code exercise · python

Run it: the loop visits each character in order, then len reports the character count of banana.

Counting characters with the accumulator

Combine the string loop with lesson 5-3's accumulator and lesson 4-2's if, and you can answer questions about any text. How many times do a or i appear in "programming"?

count = 0
for letter in "programming":
    if letter == "a" or letter == "i":
        count = count + 1
print(count)

Trace it: the letters are p-r-o-g-r-a-m-m-i-n-g, the condition is True at a and at i, so count ends at 2. This start-check-update shape is precisely how a real password validator counts digits or special characters before accepting a signup.

Quiz

What does this print? for letter in "hi": print(letter)

Code exercise · python

Your turn. Count how many times the letter s appears in "mississippi" using a loop, an if, and a count accumulator. Print only the final count (expected: 4).