lettura simple

Python's swapcase() Method

Have you ever wanted to flip the case of every letter in a string, in Python? Well, that's where Python's swapcase() method enters the scene.

text.swapcase()

You can call upon this method with any string object.

This method returns a new string where all lowercase letters are now uppercase and vice versa.

But, don't get tripped up. Python's swapcase() method doesn't tinker with the original string. Instead, it generates a brand-new string with the characters' cases flipped. So, if your aim is to change the original string, you'll need to assign the swapcase() method's result back to the original string variable.

Let's dive right into a practical example, shall we?

First, let's assign a string to a variable we'll call "text".

>>> text = "Hello World!"

Now, let's bring the swapcase() method into play on our "text" object.

>>> text.swapcase()

Just like that, you get a brand-new string where the uppercase letters are now lowercase, and, you guessed it, vice versa.

hELLO wORLD!

Bear in mind, any non-alphabetic characters, such as the exclamation point (!) in our string, remain untouched by the swapcase() method. They're just spectators to the case-flipping action.

Also, our original string? Still intact, holding its starting value of "Hello World!"

If you're looking to shake up the content of our "text" object, you'll need to assign the result of the swapcase method right back to the "text" variable.

>>> text = text.swapcase()

Doing this overwrites the "text" variable with the fresh, case-swapped string.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin