Python Text Processing - String Immutability
In python, the string data types are immutable. Which means a string value cannot be updated. We can verify this by trying to update a part of the string which will led us to an error.
Checking Immutability of a String
main.py
# Can not reassign t= "Tutorialspoint" print(type(t)) t[0] = "M"
Output
When we run the above program, we get the following output
<class 'str'>
Warnings/Errors:
Traceback (most recent call last):
File "/home/cg/root/31c1433c/main.py", line 4, in <module>
t[0] = "M"
~^^^
TypeError: 'str' object does not support item assignment
Checking Memory Location of Letters of a String
We can further verify this by checking the memory location address of the position of the letters of the string.
main.py
x = 'banana'
for idx in range (0,5):
print(x[idx], "=", id(x[idx]))
Output
When we run the above program we get the following output. As you can see above a and a point to same location. Also N and N also point to the same location.
b = 11817208 a = 11817160 n = 11817784 a = 11817160 n = 11817784