145

I try to do a simple string replacement, but I don't know why it doesn't seem to work:

X = "hello world"
X.replace("hello", "goodbye")

I want to change the word hello to goodbye, thus it should change the string "hello world" to "goodbye world". But X just remains "hello world". Why is my code not working?

martineau
  • 112,593
  • 23
  • 157
  • 280
Katherina
  • 2,083
  • 6
  • 26
  • 34

3 Answers3

247

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", 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.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

cs95
  • 330,695
  • 80
  • 606
  • 657
Tadeck
  • 125,377
  • 26
  • 148
  • 197
  • 1
    Pedantic point: strings can be mutated for `x += 'a'` special case, e.g. https://stackoverflow.com/a/40996908/6260170 – Chris_Rands Oct 08 '18 at 15:24
  • @Chris_Rands: Looks like you are right, but from outside it does not have a real mutability effect - some implementations check if this is really used, and if not (so mutability would not be observed), it would actually mutate. Is that true? – Tadeck Oct 09 '18 at 16:35
  • @Tadeck Well I think it is *real* but it's merely a CPython optimisation and not directly relevant here (that's why I said I was being pedantic) – Chris_Rands Oct 11 '18 at 20:29
1

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

user1767754
  • 21,126
  • 14
  • 125
  • 152
-2

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]