Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String replace doesn't work [duplicate]

Tags:

python

string

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?

like image 809
user5977110 Avatar asked Jan 29 '26 05:01

user5977110


1 Answers

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")
like image 146
zondo Avatar answered Jan 30 '26 17:01

zondo