9.14. The Accumulator Pattern with Strings¶

Combining the in operator with string concatenation using + 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 nonvowel 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. 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 eachChar != 'a'  and eachChar != 'e'  and eachChar != 'i'  and
eachChar != 'o'  and eachChar != 'u'  and eachChar != 'A'  and
eachChar != 'E'  and eachChar != 'I'  and eachChar != 'O'  and
eachChar != 'U':

sWithoutVowels = sWithoutVowels + eachChar


Look carefully at line 6 in the above program (sWithoutVowels = sWithoutVowels + eachChar). 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 sWithoutVowels will be the old value of sWithoutVowels concatenated with the value of eachChar. We are building the result string character by character.

Take a close look also at the initialization of sWithoutVowels. 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.

(ch08_acc2)

strings-14-1: What is printed by the following statements:

s = "ball"
r = ""
for item in s:
r = item.upper() + r
print(r)

• Ball
• Each item is converted to upper case before concatenation.
• BALL
• Each character is converted to upper case but the order is wrong.
• LLAB
• Yes, the order is reversed due to the order of the concatenation.

Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

Next Section - 9.15. Turtles and Strings and L-Systems