I tried this code to do simple string replacement:
X = "hello world"
X.replace("hello", "goodbye")
Why doesn’t X change, from "hello world" to "goodbye world"?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is because strings are immutable in Python.
Which means that
X.replace("hello","goodbye")returns a copy ofXwith replacements made. Because of that you need to replace this line:with this line:
More broadly, this is true for all Python string methods that change a string’s content, e.g.
replace,strip,translate,lower/upper,join,…You must assign their output to something if you want to use it and not throw it away, e.g.
and so on.