pythonstring

Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?


I wrote this Python program to do a simple string replacement:

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

After this, the value of X was "hello world". Why didn't it changed to "goodbye world" instead?


Solution

  • 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 to 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, 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.