Lessons · Python · strings cannot be changed
Text cannot be changed, only replaced
String methods hand back a NEW string. The original is never altered.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Cleaning up what a person typed is constant work: trimming spaces, fixing case, removing characters. If you forget to catch the result, nothing appears to happen and the bug is invisible.
How to think about it
Ask: did I CATCH what that gave me? If a line calls a string method and does not assign or use the result, that line does nothing at all.
Worked example
name = " Ada "With spaces a person accidentally typed.
name.strip()Produces "Ada" and throws it away. name is unchanged. This line accomplishes nothing.
name = name.strip()Catches the new string. Now name is "Ada".
print(name.upper())Prints ADA, and name itself is still "Ada".
Your turn
Store the lowercase version of a name.
name = "ADA" name = name.() print(name)
Solve one with the tests running
The trap
Writing name.strip() on its own and expecting name to change. It is the most common silent no-op in Python, and nothing warns you.
Practise strings cannot be changed on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.