0

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?

3
  • You can't. You can make a new string. Commented Dec 20, 2019 at 1:23
  • s.swapcase() returns a new string, it doesn't modify the string. Commented Dec 20, 2019 at 1:23
  • s = s.swapcase() does not modify the string, it creates a new string then it assigns that string to the variable s, and is ultimately the new string that is returned from your function Commented Dec 20, 2019 at 1:33

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Your function is not modifying a string object. It's modifying a name assigned to it. When you assign directly, like this,

s = "abc"
s[2] = "z"

...you are saying "change the third character in this particular string object to 'z'." On the other hand, if you assign twice, like this,

s = "abc"
s = "abz"

...you are saying "change the name, s, to refer to a new string object." This applies whether it's created as a local variable (as above) or as a function argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.