I want to know that if Python strings are immutable then why does this piece of code works and how it works.
a = input()
for i in a:
if i.isupper():
print(i.lower(), end='')
else:
print(i.upper(), end='')
This changes the characters in the string. Before as I knew that strings are immutable I used to convert it in list and then change it and join the list back to string. Now I think all the code I had written back then was worthless effort.
Strings in Python are immutable which means that once a string variable is assigned to a string (For eg a ='Hello') the contents of the string cannot be changed unlike the list object.
In the code above you are in a way transforming your string and not changing the contents of your string variable.
a=input()
for i in a:
if i.isupper():
print (i.lower(),end='')
else:
print (i.upper(),end='')
print(a)
If you would run this code you will see that the value of a is the same which you entered. The strings methods lower() and upper() just returns a copy of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With