Skip to content

Processing text with loops

Loop over a string's characters to count vowels, reverse a word and test a palindrome, building results with a counter or a string accumulator.

It opens on

A loop walks through "Programming" letter by letter and counts the vowels. Does it count 3 or 4?

Why it matters

Many text tasks have no ready-made method, such as checking a password's rules, cleaning names or validating codes, and the loop over characters with an accumulator is the pattern behind them; reversing and palindromes are classic first exam and interview questions.

Good to know first

  • Loop patterns: a counter or total updated inside a loop
  • String methods and immutability: strings cannot change, so new ones are built, and lower returns a new string

Step by step

  1. Counting characters

    Loop over a string's characters with for ch in s, and count those that pass a test.

    For "Programming" the vowels are o, a and i, so it returned 3, which answers the opening question.

    calls

    A common mix-up

    A loop over a string needs indexes, for i in range(len(s)), to reach the characters.

    In fact: For ch in s gives them directly; indexes are only needed when the position itself matters.

  2. Building a string

    Build a new string with an accumulator, by adding characters at the end or the front, and trace it.

    So reverse("stressed") returned desserts. Each character went in front of the ones before it, so the last came first.

    A common mix-up

    Result + ch and ch + result give the same string.

    In fact: String + is not commutative; the order of the two pieces is the order in the result.

  3. Palindromes

    Test a palindrome by cleaning a string to its letters in lower case and comparing it with its reverse.

    This is the filter pattern from reverse's last step, and is_palindrome reuses reverse rather than writing a second loop.

    A common mix-up

    Python's == ignores case, so "Racecar" == "racecaR".

    In fact: == compares characters exactly; lower() both sides first.

Try it

Write count_digits(s), and give its result for "R2-D2".Answer

The same loop with ch in "0123456789", or ch.isdigit(); it returns 2

Hint: Change only the test

Write double_letters(s) that doubles each character, and give it for "abc".Answer

Result = ""; for ch in s: result += ch + ch; return result; it gives 'aabbcc'

Hint: Add two at the end each pass

What does is_palindrome("No lemon, no melon") return, and what are its letters?Answer

True, with letters nolemonnomelon

Hint: Drop spaces and commas, lower the N

What do count_vowels("rhythm") and count_vowels("AEIOU") return?Answer

0, since y is not in the vowel string, and 5, since capitals are included.

What is result after the third pass, with c?Answer

'cba', since c goes in front of 'ba'.

Processing text with loops

30 minutes every month. No card.