Search code examples
pythonstringimmutability

If strings in Python are immutable, why can I change a string in a function?


I'm new to Python, and I'm writing a function to change the case of all characters in a string. The function itself is called swapCases(), and I'm using the library function swapcase() within my own function. Here is the code that I use to test my function:

print(swapCases("HoLa"))

In the first case, my function reads:

def swapCases(s):
    for i in range(len(s)):
        s[i] = s[i].swapcase()
    return s

When I run this code, I get a message from the compiler: "str object does not support item assignment." I Googled the message and it said that strings in Python are immutable and therefore can't be changed. However, when I change my function to this:

def swapCases(s):
    s = s.swapcase()
    return s

the function does exactly what I want, and the test prints out "hOlA." If strings are immutable in Python, why does this work? Doesn't being immutable mean that I can't change them?


Solution

  • By assigning it to the variable s, you are reassigning s. This gets rid of the reference to the old string "HoLa" and replaces it with a reference to the string returned from s.swapcases()

    In your original case, you are attempting to modify the string index by index. Doing this would be mutating the existing references, which is not allowed. This is what is meant by immutable.