Section 7.17 The Accumulator Pattern with Strings
Combining the in
operator with string concatenation (+
) and the accumulator pattern, we can write a function that removes all the vowels from a string. The idea is to start with a string and iterate over each character, checking to see if the character is a vowel. As we process the characters, we will build up a new string consisting of only the non-vowel characters. To do this, we use the accumulator pattern.
Remember that the accumulator pattern allows us to keep a “running total”. With strings, we are not accumulating a numeric total as we did in
Subsection 5.6.1. Instead we are accumulating characters onto a string.
Line 5 uses the not in
operator to check whether the current character is not in the string vowels
. The alternative to using this operator would be to write a very large if
statement that checks each of the individual vowel characters. Note we would need to use logical and
to be sure that the character is not any of the vowels.
if each_char != 'a' and each_char != 'e' and each_char != 'i' and
each_char != 'o' and each_char != 'u' and each_char != 'A' and
each_char != 'E' and each_char != 'I' and each_char != 'O' and
each_char != 'U':
str_without_vowels = str_without_vowels + each_char
Look carefully at line 6 in the above program (str_without_vowels = str_without_vowels + each_char
). We will do this for every character that is not a vowel. This should look very familiar. As we were describing earlier, it is an example of the accumulator pattern, this time using a string to “accumulate” the final result. In words, it says that the new value of str_without_vowels
will be the old value of str_without_vowels
concatenated with the value of each_char
. We are building the result string character by character.
Take a close look also at the initialization of str_without_vowels
. We start with an empty string and then begin adding new characters to the end.
Step through the function using codelens to see the accumulator variable grow.
Checkpoint 7.17.1.
What is printed by the following statements? Hint: Look at the concatenation very carefully!
str = "pins"
result = ""
for item in str:
result = item.upper() + result
print(result)
Pins
- Each item is converted to upper case before concatenation.
PINS
- Each character is converted to upper case but the order is wrong.
SNIP
- Yes, the order is reversed due to the order of the concatenation.