Python swap case of each character of a string

Python swap case of each character of a string :

Python provides one inbuilt method called swapcase() to swap all characters of a string. It swaps the uppercase characters to lowercase, lowercase characters to uppercase in a string and returns the string.

Definition :

The swapcase method is defined as below :

str.swapcase()

It returns the modified string. One more thing to note that not always s.swapcase().swapcase() == s for string s.

Example :

Now let’s try to learn how swapcase() works with an example :

python swap case of character

python swapcase example

As you can see that only the alphabets are changed, not the numbers and any other special characters.

Using swapcase() two times :

python swapcase characters

python swapcase example

As you can see that the last comparison returns False. Similar to ϕ, there are lots of other characters that will return false for swapcase().

 

You might also like :

Leave a Reply