Understand that strings are immutable objects in Python and show how to manipula
ID: 3603522 • Letter: U
Question
Understand that strings are immutable objects in Python and show how to manipulate their contents in an indirect manner by using the assignment operator. What does immutable mean? Wait, I thought that concatenation changed strings... Why is this wrong Talk through what the following code is doing. Note that the slicing operation does NOT actually change the state of the oniginal string on which it's operating s "Hello World" idx= s.find(..) half! = s[ : idx] half2 = s[idx+1 : ] news = half! + ' ' + half2Explanation / Answer
Explaination of what strings are immutable means:
Consider the following code:
a= "Car" # a points to Car
b=a # b points to the same Car
a=a+a # a points to a new location which is CarCar
# but b still points to the same Car as before.Even though a is changed , b still points to the same string. The string "Car" is not getting changed to "CarCar" , instead a new string "CarCar" is changed and the old string "Car" also still exists.This shows that string objects are immutable.
Walkthrough of the given code:
s= "Hello World" # s points to Hello World
idx=s.find(' ') # stores the location of ' ' , that is the location of space , which is 5 in this case(Note that numbering starts from 0)
half1=s[ : idx] =>half1= s[Beginning : 5] which is equal to "Hello"
half2=s[idx+1 =>half2=s[6 :Ending] which is equal to "World"
news=half1 +' ' + half2 which is equal to "Hello World"
While all this happens, no string has changed its value, instead new strings are created.First the string "Hello World" is created, then a second string "Hello" is created.Then a third string "World" is created.Finallly a fourth string "Hello World" is create.All the four strings exist separtely, and changing the value of one string later wont change the value of the other string.This is due to the immutable property of string objects
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.