9.8. The Accumulator Pattern with Strings

Strings are immutable, so they can not be changed. But it is possible to create entirely new strings. Combining string concatenation using + with a loop is the accumulator pattern with strings. With it we can create new strings from existing strings.

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.

 
1
def repeat(text: str, times: int) -> str:
2
    repeated_text: str
3
    repeated_text = ''
4
    for i in range(0, times, 1):
5
        repeated_text = repeated_text + text
6
    return repeated_text
7
8
def main() -> None:
9
    print("I love CS" + repeat("!", 10))
10
    return None
11
12
main()
13

(ch08_acc1)

The accumulator variable, repeated_text, is intiialized on line 3 to be the empty string. Every iteration of the loop, text is concatenated onto the end of repeated_text so it gets longer with each iteration. Step through the function using codelens to see the accumulator variable grow.

Python 3.3
1def repeat(text: str, times: int) -> str:
2    repeated_text: str
3    repeated_text = ''
4    for i in range(0, times, 1):
5        repeated_text = repeated_text + text
6    return repeated_text
7
8def main() -> None:
9    print("I love CS" + repeat("!", 10))
10    return None
11
12main()
Step 1 of 32
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(ch08_acc2)

Check your understanding

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

s: str
r: str
i: int
s = "ball"
r = ""
for i in range(0, len(s), 1):
    r = s[i] + r
print(r)



You have attempted 1 of 4 activities on this page
Next Section - 9.9. Characters