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 = 'T' print(name_1)
Output: TypeError: ‘str’ object does not support item assignment
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)
Do comment if you have any doubts or suggestions on these Python strings question topics.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
Very clear explanation….