Immutability, and Building Text

Strings are immutable. You cannot change a string after you create it. A method like upper gives you back new text, but it never changes the string you already have.

word = "hello"
upper = word.upper()

print(word)
print(upper)

Output:

hello
HELLO

If you try to change one character of a string, you get an error:

word = "hello"
word[0] = "H"

Output:

Traceback (most recent call last):
  File "/box/main.py", line 2, in <module>
    word[0] = "H"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

Build new text instead

word = "hello"
fixed = "H" + word[1:]
print(word)
print(fixed)

pieces = []
for name in ["ann", "bo", "cy"]:
    pieces.append(name.upper())
print(", ".join(pieces))

Output:

hello
Hello
ANN, BO, CY

"H" + word[1:] makes a new string. It puts a new first letter in front of a slice of the old word. word itself does not change.

When you build text from many pieces, put the pieces in a list with append. Then call join once at the end. If you add to a string with += in a long loop, Python can end up copying the whole string every time.

In the exercise, build a list of reversed words and join it.