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.

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 3 activities on this page
9.7. Strings are Immutable"> 9.9. Characters">Next Section - 9.9. Characters