Using Repetition with Strings¶
Learning Objectives:
- Show how the accumulator pattern works for strings.
- Show how to reverse a string.
- Show how to mirror a string.
- Show how to use a while loop to modify a string.
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, digits, 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.
- Set the accumulator variable to its initial value. This is the value we want if there is no data to be processed.
- Get all the data to be processed.
- Step through all the data using a
for
loop so that the variable takes on each value in the data. - Combine each piece of the data into the accumulator.
- Do something with the result.
Be sure to press the 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 new_string
.