-1
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

ewokx
  • 2,204
  • 3
  • 14
  • 27
  • Does this answer your question? [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – Gino Mempin Aug 03 '20 at 10:13

3 Answers3

2

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).

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

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.

Albin Paul
  • 3,330
  • 2
  • 14
  • 30
0

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.