Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strings - immutability of strings

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.

like image 733
Spell Blade Avatar asked Mar 27 '26 17:03

Spell Blade


1 Answers

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.

like image 81
Alay Majmudar Avatar answered Mar 30 '26 09:03

Alay Majmudar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!