You might have stumbled across a reoccurring phrase when reading in the String Methods documentation:
Return a copy [...]
Why do all of the string methods return a copy of the original string instead of modifying it? The reason is that it's simply impossible to modify a string in Python.
Define Immutable
Python strings are immutable, which means that you can't change a string after you created it.
However, you can always create a new string based on the initial string and apply certain changes.
How do Python Strings Change
Since Python allows you to update your variables and re-assign different values to them, you can even re-assign the old variable to the new string. This effectively replaces the way you accessed the old string value with the new string value:
name = 'codingnomads'
# Trying to change the string directly causes an error
# name[8:] = 'rmals'
# TypeError: 'str' object does not support item assignment
# You need to create a new string
new_name = name[:8] + 'rmals' # using string slicing and concatenation
print(name, new_name)
# After re-assigning the value, the old 'name' is overwritten
name = new_name
print(name, new_name)
Using this syntax allows you to continue to work with your original variable after applying the changes. The variable now points to the new, adapted string.
By now, you have learned most of the important things there are to know about strings in Python. You learned that strings are collections of characters, saw how you can slice and dice them, learned about some string methods that exist, and doubled down on the knowledge that strings are eternal and unchangeable.
Summary: Python Immutability
- Python strings are immutable
- Immutability means something that can't change
- Python creates new strings and re-assigns them to the original variable
- Replacing the old string value with the new one is Python's way of making immutable Strings changeable