Immutable objects once created, will not change in their lifetime. Python strings are immutable. You can’t change the value of the string in Python.
Why are strings in Python immutable?
Answer: Advantages of strings are immutable so that developers can’t alter the contents of the object (even by mistake). This avoids unnecessary bugs.
Strings are not only immutable there are some other objects integer, float, tuple, and bool also immutables.
Example Strings are immutable in Python
Simple example code trying to update a string which will lead us to an error. Just update J char to T char in a given string.
name_1 = "Jim"
name_1[0] = 'T'
print(name_1)
Output: TypeError: ‘str’ object does not support item assignment
Update string
Still, if you want to update the string then for it you have to create a new string object with the necessary modifications:
Using slice notation in this example.
name_1 = "Jim"
name_2 = "T" + name_1[1:]
print(name_2)
Output: Tim
Do comment if you have any doubts or suggestions on these Python strings question topics.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Very clear explanation….