String methods and immutability
Clean, search, split and join text with string methods, and show that each returns a new string because strings cannot change.
It opens on
t = "hello" and then t.upper() on a line of its own, then print(t). Does it print hello or HELLO?
Why it matters
Cleaning and splitting text, user input, file lines and CSV fields, is a large share of real programs, and forgetting that s.upper() returns a new string instead of changing s is one of the commonest beginner bugs.
Good to know first
- String indexing and slicing: s[i], s and that slices make new strings
- Defining and calling functions: a call returns a value that can be assigned
Step by step
Methods return new strings
Call a string method with dot notation and keep its result, seeing that the original string is unchanged.
The run printed hello, which answers the opening question. No string method can change the string it is called on.
A common mix-up
s.upper() changes s.
In fact: It returns a new string; s is unchanged unless the result is assigned back to it.
The everyday methods
Use strip, lower, find, replace, split and join, and predict each result.
The run printed -1 and Ado Loveloce. replace changes every match, and the capital A stayed, since "a" and "A" are different characters.
methods and results, all
A common mix-up
Split() and split(" ") are the same.
In fact: Split() treats any run of whitespace as one separator, while split(" ") splits at every single space and keeps empty pieces.
Immutability and cleaning a line
Explain that strings are immutable, build a changed copy instead, and clean and split a line of text into fields.
w[0] = "P" raised TypeError, 'str' object does not support item assignment.
A common mix-up
A string's character can be changed by assigning to s[i], as a list's can.
In fact: Strings are immutable, and s[i] = ... raises TypeError.
Try it
s = "Python"; s.lower(); print(s); What is printed, and how do you fix it to print python?Answer
Python; write s = s.lower() before the print
Hint: Keep the result
What does "banana".replace("an", "AN") return, and what does "banana".find("n") return?Answer
'bANANa' and 2
Hint: Replace changes every match
line = "x=5\n". Which expression gives the number 5 as an int?Answer
Int(line.strip().split("=")[1])
Hint: Strip, split at =, take the second piece, convert
Line 2 calls t.upper() and does nothing with the result. What does line 3 print?Answer
The word still in small letters, since upper returned a new capitalised string that was thrown away, and t still names the original.
What do s.find("love") and s.replace("a", "o") return?Answer
-1, since find is case sensitive and there is no small l in Love's place; and 'Ado Loveloce', with every small a replaced.
