swapcase() in Python

In this article, we would cover swapcase() method in Python. The swapcase() method basically converts all the uppercase characters to lowercase and vice versa. Following is the syntax of swapcase() method –

str.swapcase()

We understand it more with appropriate examples next.

swapcase() in Python

Example I. Let’s say we have a string x,

x = "Hello, how are you? I am Fine"

Now, if we want to convert all uppercase characters to lowercase and lowercase characters to uppercase. Then, we use swapcase() in Python –

y = x.swapcase()

We store the outcome in variable y. To print the outcome, we use print() method –

print(y)

This will return with –

hELLO, HOW ARE YOU? i AM fINE

It returns with the expected outcome. All lowercase and uppercase characters are converted to uppercase and lowercase characters respectively.

Example II. Although, the above example will suffice. But, still we introduce the element of integer values in the string and see how swapcase() method would react to it. Again, we use the string x

x = "He4lo, how a7e you? I 3m F67e"

Next, we use swapcase() method to get the desired outcome and store it in variable y,

y = x.swapcase()

To print the outcome, we use print() method –

print(y)

It would return with –

hE4LO, HOW A7E YOU? i 3M f67E

As expected, integer values didn’t have any impact on our outcome. Uppercase characters were converted to lowercase and vice versa.

In conclusion, we have discussed swapcase() in Python.

Similar Posts