9.12. The Accumulator Pattern with StringsΒΆ
We can also accumulate strings rather than accumulating numbers, as youβve seen before. The following program isnβt particularly useful for data processing, but we will see more useful things later that accumulate strings.
Look carefully at line 4 in the above program (ac = ac + c + "-" + c + "-"
). In words, it says that the
new value of ac
will be the old value of ac
concatenated with the current character, a dash, then the
current character and a dash again. We are building the result string character by character.
Take a close look also at the initialization of ac
. We start with an empty string and then begin adding
new characters to the end. Also note that I have given it a different name this time, ac
instead of
accum
. Thereβs nothing magical about these names. You could use any valid variable and it would work the
same (try substituting x for ac everywhere in the above code).
Check your understanding
- 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.
seqmut-10-2: What is printed by the following statements:
s = "ball"
r = ""
for item in s:
r = item.upper() + r
print(r)
Assign an empty string to the variable output
. Using the range
function, write code to make it so that the variable output
has 35 a
s inside it (like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
). Hint: use the accumulation pattern!