x = "hello, world"
print(x.replace("h","j")
so from this code you can change the letter h to j so that means it is mutable
x = "hello, world"
print(x.replace("h","j")
so from this code you can change the letter h to j so that means it is mutable
so that means it is mutable
No, Python strings are not mutable. str.replace
(and any other string method) return a new string.
If strings were mutable then the following code
x = "hello, world"
x.replace("h","j")
print(x)
Would output jello, world
(which it does not).
It doesnt mean that string is mutable it means that we are creating a new string in the replace
method.
>>> a= "ababa"
>>> id(a)
48421600L
>>> id(a.replace('a','c'))
48419776L
>>>
as you can see from the id of the strings, that they are two different strings. Or you can use the is
operator for comparison also.
Strings are immutable in python.
>>> x = 'hello, world'
>>> x
[OUT]: 'hello, world'
>>> id(x)
[OUT]: 4400926320
>>> x = x.replace('h','j')
>>> x
[OUT]: 'jello, world'
>>> id(x)
[OUT]: 4402216304
When you you try to modify a value of a string object it points to a new string with different location in the memory as strings are immutable. id(x) returns the memory address of x.