Sub topic 1
Strings are immutable: methods return new strings
Prerequisites
This chapter assumes you know basic Python syntax (variables, expressions, and function calls). It also assumes you are comfortable with str literals and indexing, know what lists and tuples are, and can read simple if statements and for loops.
What immutable means
A Python str is immutable. Once a string object exists, its characters cannot change. Every string method that appears to modify text actually builds a new string and returns it. The original object stays exactly as it was.
s = "abc"
t = s.upper()
print(s) # abc
print(t) # ABCCalling s.upper() did not touch s. It returned a new string "ABC", which the code stored in t. If you want to keep a result, you must assign it to a name.
The most common mistake
Beginners often call a method and discard the result:
name = " Ada "
name.strip()
print(repr(name)) # ' Ada 'The call produced a trimmed string, but nothing held onto it, so Python threw it away. The fix is to assign the result. You can assign it back to the same name:
name = " Ada "
name = name.strip()
print(repr(name)) # 'Ada'Here name now points to the new string. The old string " Ada " is no longer referenced and Python will reclaim it.
You cannot assign to a position
Immutability also explains why item assignment fails:
word = "cat"
try:
word[0] = "b"
except TypeError as error:
print(error)Python raises TypeError because a string does not support changing one character in place. To get "bat", build a new string from pieces:
word = "cat"
word = "b" + word[1:]
print(word) # batChecking identity
The is operator tests whether two names refer to the same object. It shows that a method returns a different object.
s = "abc"
t = s.upper()
print(s is t) # False
print(s == "abc") # TrueSome methods return the original object when nothing needs to change. For example, "ABC".upper() may return the same object. Do not rely on this. Treat every result as a new value, and compare strings with ==, not is.
Why Python works this way
- Strings can safely be used as dictionary keys, because their value never changes after hashing.
- Several names can share one string without one name's changes surprising another.
- Python can reuse string objects internally.
The cost is that building a large string by repeated changes creates many temporary copies. Later chapters show join as the usual remedy.
Summary of the rule
- A string method never changes the string it is called on.
- The method returns a new string (or another value, such as an index or a list).
- Assign the result to a name if you want to keep it.
Exercise
What do the two print calls show? text = "Python" text.lower() print(text) text = text.lower() print(text)
Show answer
The first print shows Python, because the result of the first text.lower() call was discarded and the original string is unchanged. The second print shows python, because the result was assigned back to text.
Exercise
A learner writes s = "hello" and then s[0] = "J" to get "Jello". What error occurs, and how do you get "Jello"?
Show answer
Python raises a TypeError because strings do not support item assignment. Build a new string instead, for example s = "J" + s[1:], or use s = s.replace("h", "J", 1).