Sub topic 1
Strings are immutable: methods return new values
Every split and join operation in this tutorial rests on one fact about Python strings: they cannot be changed after they are created. This chapter explains what that means, how it affects the way you call string methods, and which mistakes it causes.
Prerequisites
This chapter assumes you can:
- Run a Python script or use the REPL (the interactive prompt).
- Work with strings, lists and tuples.
- Call a method and read its return value.
- Write a basic
forloop and a generator expression.
What immutable means
A string is an immutable sequence. Once Python creates a str object, its characters never change. You can read characters by index, but you cannot assign to them.
word = "python"
print(word[0]) # p
try:
word[0] = "P"
except TypeError as error:
print(error) # 'str' object does not support item assignmentLists behave differently. A list is mutable, so items[0] = "P" works and changes the same list object. Strings give you no such operation.
Methods return new values
Because a string cannot change, a string method cannot modify it. The method builds a new object and returns it. The original stays as it was.
name = "alpha"
upper = name.upper()
print(name) # alpha
print(upper) # ALPHAThe methods you will meet in this tutorial work the same way. split does not alter the string it is called on. It returns a new list that holds new strings.
text = "a,b,c"
parts = text.split(",")
print(text) # a,b,c
print(parts) # ['a', 'b', 'c']The following diagram shows the flow. The input string is read, a new value is produced, and the input is untouched.
The most common mistake: discarding the result
A frequent error is to call a method and ignore what it returns. Python does not complain, because the call is valid. It simply computes a new value and throws it away.
line = " hello "
line.strip() # result is discarded
print(repr(line)) # ' hello '
line = line.strip() # rebind the name to the new value
print(repr(line)) # 'hello'The fix is to use the return value. Either assign it to a name, as above, or pass it straight on to the next step.
cleaned = " a, b ,c ".strip().split(",")
print(cleaned) # ['a', ' b ', 'c']Chaining works because each method returns a new string, and the next method is called on that new string. In the example, strip() returns a string, and split(",") is then called on it.
Rebinding is not mutation
When you write line = line.strip(), you are not changing the old string. You are making the name line point at a different object. The old string is discarded if nothing else refers to it.
The same applies to += on strings. It looks like in-place modification, but it creates a new string and rebinds the name.
a = "abc"
b = a
a += "d"
print(a) # abcd
print(b) # abcThe name b still refers to the original "abc". If strings were mutable, b would have changed too. This behaviour is why you can pass strings to functions or store them in dictionaries without worrying that someone else will alter them. It is also why building a long string with repeated += has a cost, which a later chapter on join examines.
Quick reference
| Operation | Changes the original? | What you get |
|---|---|---|
| `s.upper()` | No | New string |
| `s.split(",")` | No | New list of new strings |
| `s[0] = "x"` | Not allowed | `TypeError` |
| `s += "x"` | No, the name is rebound | New string bound to `s` |
Checking identity
If you want to confirm that two names refer to different objects, compare them with is. The id() function gives the same information as a number.
original = "hello"
changed = original.replace("h", "j")
print(original is changed) # False
print(original, changed) # hello jelloAvoid relying on is for string equality in real code. Use == to compare contents. The check above is only a way to see that a new object was created.
Summary of the rule
- Strings cannot be modified in place.
- Every string method returns a result and leaves the original alone.
- If you want the result, assign it or chain another call onto it.
- A discarded return value is a silent bug, not an error.
Exercise
The code below is meant to split a line on commas after removing surrounding whitespace, but fields is printed as [' x', 'y '] with the spaces still present. Why, and how do you fix it?
line = " x,y "
line.strip()
fields = line.split(",")
print(fields)
Show answer
line.strip() returns a new string, but the result is discarded, so line still holds the original text with its spaces. Fix it by using the return value: line = line.strip() before splitting, or fields = line.strip().split(","). The result is ['x', 'y'].