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.
def repeat(text: str, times: int) -> str:
repeated_text: str
repeated_text = ''
for i in range(0, times, 1):
repeated_text = repeated_text + text
return repeated_text
def main() -> None:
print("I love CS" + repeat("!", 10))
return None
main()
(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
Step 1 of 32 line that has just executed next line to execute Visualized using Online Python Tutor by Philip Guo |
| |||||||||||||||||||||||||||
(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)