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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With