Sub topic 10
Strings Cannot Be Changed in Place
This chapter assumes you can run Python code and use print() and len(). It also assumes you can read a simple try/except block and know that s[0], s[-1] and s[a:b] read characters from a string. Here you will see what happens when you try to write to a string, and how to get the same result by building a new one.
What "immutable" means
An immutable object cannot be modified after it is created. Python strings are immutable. Indexing lets you read a character, but it does not let you assign to one.
s = "Python"
try:
s[0] = "J"
except TypeError as e:
print(e)
print("J" + s[1:])
print(s)This prints three lines:
'str' object does not support item assignment
Jython
PythonThe error is a TypeError, not an IndexError. Index 0 is valid, so the index is not the problem. The problem is that the str type has no operation for assigning to a position.
The last line shows the original is untouched. "J" + s[1:] creates a new string, "Jython". The old string "Python" keeps its value.
Rebinding is not mutation
A variable name is a label that points at an object. Assigning to the name moves the label. It does not change the object that the label pointed at before.
a = "Python"
b = a
a = "J" + a[1:]
print(a)
print(b)
print(a is b)The output is:
Jython
Python
FalseBoth a and b first pointed at the same string. The assignment a = ... pointed a at a new string. b still points at the old one, so it was not affected.
This is a safety property. Because no code can change a string, you can pass a string to any function and be sure it comes back unchanged. Strings can also be used as dictionary keys, because their hash value never changes.
Building new strings from slices
To "change" a string, you slice out the parts you want to keep and join them with the new parts. Three operations cover most cases.
| Operation | Pattern | Example result for `"Python"` |
|---|---|---|
| Replace one character at index `i` | `s[:i] + new + s[i+1:]` | `i=0`, `new="J"` gives `Jython` |
| Insert before index `i` | `s[:i] + new + s[i:]` | `i=2`, `new="-"` gives `Py-thon` |
| Delete the character at index `i` | `s[:i] + s[i+1:]` | `i=2` gives `Pyhon` |
The replace and delete patterns skip index i by starting the second slice at i+1. The insert pattern keeps index i by starting the second slice at i.
text = "Python"
print(text[:0] + "J" + text[1:])
print(text[:2] + "-" + text[2:])
print(text[:2] + text[3:])The output is:
Jython
Py-thon
PyhonThese patterns rely on the slice rules from earlier chapters. text[:2] is "Py" and text[2:] is "thon". The two pieces always add back up to the original, so inserting between them is safe. The replacement string does not need to be one character long. "Python"[:2] + "XYZ" + "Python"[3:] is a valid way to swap one character for three.
The negative-index trap
The replace pattern s[:i] + new + s[i+1:] works for i >= 0. For negative indexes it silently gives wrong output.
s = "Python"
i = -1
print(s[:i] + "!" + s[i+1:])This prints Pytho!Python, not Pytho!. With i = -1, the second slice is s[0:]. Adding 1 to -1 gives 0, and 0 means "from the start", not "from the end". The whole string is appended again.
The fix is to turn a negative index into its non-negative equivalent before slicing. You should also check the range yourself, because slices never raise errors and would hide a bad index.
def replace_at(text, index, new):
if not -len(text) <= index < len(text):
raise IndexError("string index out of range")
if index < 0:
index += len(text)
return text[:index] + new + text[index + 1:]
print(replace_at("Python", 0, "J"))
print(replace_at("Python", -1, "!"))
try:
replace_at("Python", 6, "x")
except IndexError as e:
print(e)The output is:
Jython
Pytho!
string index out of rangeWithout the range check, replace_at("Python", 6, "x") would return "Pythonx", because text[:6] is the whole string and text[7:] is empty. The out-of-range slice behavior is useful for reading, but it hides mistakes when you are writing.
Methods return new strings
String methods follow the same rule. Methods such as upper(), replace(), strip() and title() never change the string they are called on. They return a new string. A common beginner error is calling a method and discarding the result.
name = "ada"
name.upper()
print(name)
name = name.upper()
print(name)The output is:
ada
ADAThe first call computes "ADA" and throws it away. Only the assignment keeps the result. Python gives no warning for the first form, since an expression whose value is ignored is legal code.
The replace() method is often a better choice than slicing when you know what text you want to change rather than where it is.
s = "banana"
print(s.replace("a", "o"))
print(s.replace("a", "o", 1))
print(s)The output is:
bonono
bonana
bananaThe third argument is a count that limits how many occurrences are replaced, counting from the left. Use slicing when the position is what matters, and replace() when the content matters.
Many edits: use a list
Every slice-and-join creates a new string and copies the characters. One edit on a short string costs almost nothing. Hundreds of edits on a long string do repeated copying, and each edit takes time proportional to the string length.
If you need to change many positions, convert the string to a list of characters. Lists are mutable and support item assignment. Edit the list, then join it back into a string once.
chars = list("Python")
chars[0] = "J"
chars[-1] = "N"
print("".join(chars))
chars = list("hello world")
chars[::2] = [c.upper() for c in chars[::2]]
print("".join(chars))The output is:
JythoN
HeLlO WoRlDThe second part uses an extended slice on the left side of an assignment. This is allowed for lists, and the replacement must have exactly as many items as the slice selects. The same statement on a string would raise a TypeError.
The same idea applies to building a string piece by piece. Collect the pieces in a list and call "".join(pieces) once at the end. This is the standard approach for large loops. Repeated result += piece can be slow on some Python implementations. CPython sometimes optimizes it, but you should not depend on that.
Edge cases and details
- Empty replacement.
s[:i] + s[i+1:]with no new text deletes one character. For an empty string there is no validi, andreplace_at("", 0, "x")raisesIndexError. - Full-slice copies.
s[:]gives you a string equal tos. In CPython, for an exactstr, it can return the same object, because a copy of an immutable object is never needed. You should not rely on this. It only means that copying with[:]is cheap and harmless. - Identity and equality. Use
==to compare string content. Theisoperator tests whether two names point at the same object, and for strings the answer can depend on interning and other implementation details. - Other immutable types. Tuples and bytes are also immutable sequences. They support the same indexing and slicing, and you change them in the same way, by building a new one. Lists and
bytearrayare mutable. - Byte-like strings. If you really need an editable sequence of bytes,
bytearrayallowsb[0] = 74. It stores integers, not text characters.
Summary of the working model
- A string never changes. Operations that look like changes return new strings.
s[i] = xraisesTypeError, whatever the value ofi.- Assigning to a name moves the name. Other names keep pointing at the old string.
- Slice-and-join is the basic tool for replace, insert and delete, and negative indexes need normalizing.
- Ignoring the return value of a string method is a silent bug.
- For many edits, use a list and join once.
Exercise
What do the two print calls output? s = "data" t = s s = s[:1].upper() + s[1:] print(s, t)
Show answer
It prints "Data data". The slicing expression builds a new string "Data" and the name s is rebound to it. The name t still points at the original string "data", which was never modified.
Exercise
Write a function insertat(text, index, new) that inserts new before the character at index, where 0 <= index <= len(text) and an index equal to len(text) appends. Raise IndexError for any index outside that range. Then say what insertat("Python", 2, "-") returns.
Show answer
def insertat(text, index, new): if not 0 <= index <= len(text): raise IndexError("insert index out of range") return text[:index] + new + text[index:] The call insertat("Python", 2, "-") returns "Py-thon". The check is needed because slices clamp out-of-range bounds, so without it insert_at("Python", 99, "-") would quietly return "Python-".
Exercise
Why does this code leave the string unchanged, and how do you fix it? word = " hello " word.strip() print(repr(word))
Show answer
strip() returns a new string and does not modify word. The returned value is thrown away, so word still holds " hello ". The fix is to assign the result: word = word.strip(), which makes print(repr(word)) show 'hello'.