Using Repetition with Strings

Learning Objectives:

Python already has built in the ability to play with words or strings, just like how we played with numbers in the last chapter. A string is a collection of letters, numbers, and other characters. A Python for loop knows how to step through letters, and addition (+) appends strings together. What’s cool is that the same accumulator pattern works.

As a reminder, here are the five steps in the accumulator pattern.

  1. Set the accumulator variable to its initial value. This is the value we want if there is no data to be processed.

  2. Get all the data to be processed.

  3. Step through all the data using a for loop so that the variable takes on each value in the data.

  4. Combine each piece of the data into the accumulator.

  5. Do something with the result.

Be sure to press the audio tour button to get an explanation for how this program works.

Run this program. Enh, not that interesting, eh? It just copies all the letters from phrase to newString.

You have attempted of activities on this page