Immutable means we cannot change the original string after creating it.
In Python, strings are immutable because Python does not allow us to modify individual characters of an existing string.
- Example:
name = "Python"
name[0] = "J"
print(name)
Output:
TypeError:
'str' object does not support item assignment
Why?
Because we are trying to change the first character of the existing string from P to J.
Python does not allow this.
- How can we change a string?
We cannot modify the original string, but we can create a new string.
name = "Python"
name = "J" + name[1:]
print(name)
Output:
Jython
Top comments (0)