3

I am trying to do a replace for something in a string. Here is the code I am testing:

stringT = "hello world"
print(stringT)
stringT.replace("world", "all")
print(stringT)

I would expect the second output to say 'hello all' but it says 'hello world' both times. There are no errors, the code runs fine, it just doesn't do anything. How do I fix this?

user5977110
  • 85
  • 1
  • 3
  • 9
  • 1
    `str.replace()` doesn't change your string in-place. You need to reassign the result after replacing. – Mazdak Feb 26 '16 at 15:42

1 Answers1

10

Strings are immutable. That means that they cannot be changed. stringT.replace(...) does not change stringT itself; it returns a new string. Change that line to:

stringT = stringT.replace("world", "all")
zondo
  • 19,901
  • 8
  • 44
  • 83