Sub topic 10
Strings cannot be changed in place
This chapter assumes you can read a try/except block and that you know zero-based, negative and slice indexing from the earlier chapters. Here you will see what happens when you try to change a string through an index, and how to get the change you wanted.
Reading works, writing does not
A Python string is immutable: once created, its contents cannot change. Indexing and slicing only read from it. Assigning to an index fails:
s = "Python"
try:
s[0] = "J"
except TypeError as e:
print(e)
print("J" + s[1:])This prints 'str' object does not support item assignment, then Jython. The original s is untouched. The expression "J" + s[1:] builds a new string out of a new first character and a slice of the old one.
Building a new string from slices
To change a character at position i, take everything before it, add the replacement, then add everything after it:
def replace_at(text, i, new_char):
return text[:i] + new_char + text[i + 1:]
s = "Python"
t = replace_at(s, 0, "J")
print(s)
print(t)
print(replace_at(s, -1, "!"))The output is Python, Jython and Python... check the last line carefully: with i = -1, text[:-1] is Pytho and text[0:] is the whole string, so the result is PythoPython. That is a bug. The slice text[i + 1:] for i = -1 becomes text[0:].
The `i + 1` trick breaks for negative indexes. When `i` is `-1`, `i + 1` is `0`, so the "after" slice is the whole string. Convert a negative index first, for example with `i %= len(text)`, or restrict the function to non-negative indexes.A corrected version:
def replace_at(text, i, new_char):
if not -len(text) <= i < len(text):
raise IndexError("string index out of range")
i %= len(text)
return text[:i] + new_char + text[i + 1:]
print(replace_at("Python", 0, "J"))
print(replace_at("Python", -1, "!"))This prints Jython and Pytho!. The range check keeps the same IndexError behavior that a plain index would have. Without it, an out-of-range i would be silently wrapped or ignored by the slices.
Rebinding is not mutation
This code looks like it changes a string, but it does not:
s = "Py"
before = id(s)
s += "thon"
print(s)
print(id(s) == before)It prints Python and then False. The += operator creates a new string and points the name s at it. The old string is unchanged, and it is discarded if nothing else refers to it.
The same applies to string methods. They return new strings and never modify the original:
s = "python"
s.upper()
print(s)
s = s.upper()
print(s)The first print shows python, because the result of s.upper() was thrown away. The second shows PYTHON.
Many edits at once
Each slice-and-join copies the whole string. For one or two edits that is fine. For many edits, convert to a list, change the list in place, and join it back:
chars = list("Python")
chars[0] = "J"
chars[-1] = "N"
print("".join(chars))This prints JythoN. Lists are mutable, so item assignment works, and "".join(chars) makes a single new string at the end.
When you want to replace by content rather than by position, str.replace() is simpler than slicing: "Python".replace("P", "J") returns 'Jython'.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `s[0] = "J"` | `TypeError` | Build a new string with slices |
| `s.upper()` with no assignment | Result is discarded | `s = s.upper()` |
| `text[:i] + c + text[i + 1:]` with `i = -1` | Wrong result, no error | Normalize `i` first |
| Many `+=` edits in a loop | Slow copying | Use a list and `"".join()` |
Exercise
Write remove_at(text, i) for a non-negative i that returns text without the character at index i. What does remove_at("Python", 2) return, and why is text unchanged afterward?
Show answer
def remove_at(text, i): return text[:i] + text[i + 1:]. The call returns 'Pyhon'. Strings are immutable, so the function builds a new string from the slices 'Py' and 'hon'. The original 'Python' is never modified.