0
We all know that there are two types of Data types in Python ,i.e Mutable and other is immutable. In simple words, Mutable object can be change after its created whereas immutable object can’t
String,tuple,int,float,bool is example of immutable whereas list,dict and set are example of mutable data type.
Lets take an example of string data type :
We have string S=’Sujil’ and we need to change char ‘j’ to ‘n’ to make S=’Sunil’
>>> S ='Sunil'
>>> S ='Sujil'
>>> S=[2] = 'n'
File "<input>", line 1
SyntaxError: can't assign to literal
We will get the SyntaxError , means we cannot change the defined string as string is Mutable data type .
Is there any way to change the Mutable data type string S=’Sujil’ to S=’Sunil’.
Yes , we can so the same . There is 3 way to do as below , choose the best way for urself.
Way 1:
>>> S ='Sujil'
>>> S
'Sujil'
>>> S = S[:2]+'n' +S[3:]
>>> S
'Sunil'
>>> type(S)
<class 'str'>
Way 2:
>>> S = 'Sujil'
>>> S
'Sujil'
>>> type(S)
<class 'str'>
>>> S =S.replace('j','n')
>>> S
'Sunil'
Way 3:
>>> S = 'Sujil'
>>> type(S)
<class 'str'>
>>> Continue reading