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?
s.swapcase()returns a new string, it doesn't modify the string.s = s.swapcase()does not modify the string, it creates a new string then it assigns that string to the variables, and is ultimately the new string that is returned from your function