-3

I have a string S = 'spam'

When I use the method replace as S.replace('pa', 'xx')

S.replace('pa', 'xx')

The output I get is -

Out[1044]: "sxxm's"

Why then are the python strings known to be immutable ?

Sarang Manjrekar
  • 1,839
  • 5
  • 31
  • 61
  • 4
    Who says the string object `S` references itself is altered? You got a *new string* back, which was echoed. – Martijn Pieters Sep 27 '16 at 12:07
  • 1
    Try `T = S.replace('pa', 'xx')` and you'll see that `S` is unaltered afterwards. [*"Return a copy of the string with all occurrences of substring old replaced by new."*](https://docs.python.org/3/library/stdtypes.html#str.replace) – jonrsharpe Sep 27 '16 at 12:07

2 Answers2

1
S = 'spam'
S.replace('pa', 'xx')
print S

You will get the same string 'spam'

FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
-1

You are not saving the return value.

Snew = S.replace('pa', 'xx')

should work

Marshall
  • 1,353
  • 3
  • 17
  • 38