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.

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)
    
  • ball
  • Each letter is concatenated, but the order is not correct.
  • llab
  • Yes, the order is reversed due to the order of the concatenation.
You have attempted of activities on this page
9.7. Strings are Immutable"> 9.9. Characters">Next Section - 9.9. Characters