Sub topic 1
Strings are immutable: methods return new strings
Every string method in this tutorial follows one rule: it never changes the string it is called on. Methods like upper, replace, and strip build a new string and hand it back. This chapter explains that rule, shows the bugs it causes, and gives the patterns you will use for the rest of the tutorial.
Prerequisites
This chapter assumes you already know:
- Basic Python syntax: variables, expressions, and function calls.
- How
strliterals work and how to index them, such ass[0]ands[1:]. - What lists and tuples are.
- How to read simple
ifstatements andforloops.
You do not need any knowledge of the re module.
What immutable means
An object is immutable if its contents cannot change after it is created. A str is immutable. You can read any character, but you cannot overwrite one.
s = "hello"
try:
s[0] = "J"
except TypeError as e:
print(e)This prints 'str' object does not support item assignment. Python rejects the assignment because a string has no way to modify itself.
The same rule applies to every method. A method cannot edit its string, so it returns a new one.
s = "abc"
t = s.upper()
print(s) # abc
print(t) # ABCAfter the call there are two separate strings: "abc", which is still bound to s, and "ABC", which is bound to t. The method read s, built "ABC", and returned it.
The most common bug: discarding the result
If you call a method and ignore the return value, the new string is created and thrown away. The original stays as it was. Python raises no error, so the bug is easy to miss.
name = " Ada "
name.strip()
print(repr(name)) # ' Ada '
name = name.strip()
print(repr(name)) # 'Ada'The first name.strip() is a valid expression, but its result goes nowhere. The second line rebinds the name name to the trimmed copy. To keep a result, assign it to a variable, pass it to a function, or use it in an expression.
Programmers who know languages with mutable strings, or Python's list.sort() and list.append(), often expect an in-place change. Those list methods do modify the list and return None. String methods work the opposite way, so do not mix up the two conventions.
Rebinding is not mutation
Writing x = x.upper() looks like it changes x, but it only points the name x at a new string. The old string is untouched. Any other name that still refers to it sees no change.
x = "abc"
y = x
x = x.upper()
print(x) # ABC
print(y) # abcHere y kept the original string because x was rebound to a different object. This is why strings are safe to share. You never need to copy a string defensively, because nobody can modify it behind your back.
The same applies to function arguments. A function cannot alter the caller's string.
def shout(text):
text = text.upper()
return text
original = "hi"
print(shout(original)) # HI
print(original) # hiInside shout, the parameter text is rebound to a new string. The caller's original is unaffected. If you want the new value, you must return it and assign it.
Checking identity
The is operator tests whether two names refer to the same object. A transformed string is a different object from the original.
a = "abc"
b = a.upper()
print(a is b) # False
print(a == "abc") # TrueUse == to compare string values. Do not use is for that. Whether two equal strings happen to be the same object depends on the Python implementation and on details such as string interning. Your code should not rely on it.
Not every method returns a string
"Returns a new string" is the rule for the transforming methods. Searching and testing methods return other types, and none of them modify the string either.
| Method | Returns | Example result |
|---|---|---|
| `upper()`, `strip()`, `replace()` | a new `str` | `'ABC'` |
| `startswith()`, `isdigit()` | `bool` | `True` |
| `find()`, `count()` | `int` | `4` |
| `split()`, `splitlines()` | `list` of `str` | `['a', 'b']` |
| `partition()` | `tuple` of three `str` | `('key', '=', 'value')` |
Knowing the return type tells you what to do with the result. A bool goes into an if. An int from find is a position that you check against -1. A list is something you loop over or index. Later chapters cover each of these in detail.
Changing one character
Because s[0] = "J" fails, you build a new string from pieces. For a single change, slicing and concatenation are enough.
s = "hello"
t = "J" + s[1:]
print(t) # JelloFor several position-based edits, convert the string to a list of characters, change the list, and join it back. A list is mutable, so item assignment works.
s = "hello"
chars = list(s)
chars[0] = "J"
chars[-1] = "y"
print("".join(chars)) # JellyIf the edit is "replace this text with that text", replace is simpler than either approach. It is covered in its own chapter.
Building strings in a loop
Immutability has a cost. Each += on a string creates a new string, so repeated concatenation in a long loop copies text over and over. CPython can sometimes optimize this case, but the language does not guarantee it. The standard pattern is to collect the pieces in a list and join them once.
parts = []
for word in ["red", "green", "blue"]:
parts.append(word.upper())
result = "-".join(parts)
print(result) # RED-GREEN-BLUEappend mutates the list, which is cheap. join then builds the final string in a single pass. For a handful of pieces the difference does not matter, so prefer whichever version reads more clearly. Switch to the list and join pattern when the loop can run thousands of times.
Related immutable and mutable types
Immutability is a property of str, and Python has neighbors with different behavior.
bytesis immutable, likestr, but holds raw byte values.bytearrayis mutable. You can assignba[0] = 74, and it has many of the same method names asbytes.listis mutable, so it is the usual scratch space for text that you need to edit in place.
Most programs do not need bytearray for text. Work with str, and treat each method call as producing a value that you must capture.
Method calls compose
Each method returns a new str, so you can call another method on the result right away. This is the basis of the cleanup pipelines you will build later in the tutorial.
raw = " Hello World "
clean = " ".join(raw.split()).lower()
print(clean) # hello world
print(repr(raw)) # ' Hello World 'Every step creates an intermediate string, and raw is still intact at the end. If a pipeline gives an unexpected result, print each intermediate value on its own line to find the step that went wrong.
Common errors
- Calling a method and not assigning the result. The string appears unchanged.
- Trying
s[i] = value. This raisesTypeError. - Expecting a function to modify the string it receives. It can only return a new one.
- Comparing strings with
isinstead of==. - Concatenating with
+=inside a very large loop instead of usingjoin. - Treating a
boolorintresult as if it were the transformed string. For example,s = s.startswith("a")replaces your text withTrueorFalse.
Exercise
What does this code print, and why? text = "Python" text.lower() copy = text text = text.upper() print(text, copy)
Show answer
It prints PYTHON Python. The line text.lower() creates the string "python" but discards it, so text is unchanged. copy = text makes copy refer to "Python". Then text = text.upper() rebinds text to a new string, "PYTHON", and leaves the string that copy refers to alone.
Exercise
Write code that changes the third character of "cart" so the result is "cast", without using replace. Name two ways.
Show answer
Slicing: s = "cart"; print(s[:2] + "s" + s[3:]) gives cast. List conversion: chars = list("cart"); chars[2] = "s"; print("".join(chars)) also gives cast. Both build a new string, because the original string cannot be edited.
Exercise
A function is meant to clean user input but the caller still sees the dirty text: def clean(s): s = s.strip().lower() value = clean(" YES ") print(value) What is printed, and how do you fix it?
Show answer
It prints None, because the function has no return statement. The cleanup works on a new local string, which is then discarded. Fix it by adding return s at the end, or by writing return s.strip().lower(). The caller then receives yes.