How to Convert Strings to Opposite Case in Python?

Estimated read time 2 min read

To convert strings to the opposite case (uppercase to lowercase and lowercase to uppercase) in Python, you can use the swapcase() method or the str.swapcase() function. Here’s how you can do it:

Using the swapcase() method:

string = "Hello, World!"
opposite_case_string = string.swapcase()
print(opposite_case_string)  # Output: "hELLO, wORLD!"

In this example, the swapcase() method is called on the string variable, which returns a new string with the case of each character swapped. The resulting string with the opposite case is then assigned to the opposite_case_string variable and printed.

Using the str.swapcase() function:

string = "Hello, World!"
opposite_case_string = str.swapcase(string)
print(opposite_case_string)  # Output: "hELLO, wORLD!"

In this example, the str.swapcase() function is called with the string variable as an argument. It returns a new string with the case of each character swapped, which is then assigned to the opposite_case_string variable and printed.

Both the swapcase() method and the str.swapcase() function provide the same result of converting the case of the string characters to their opposite case. The choice between them depends on whether you prefer the method syntax or the function syntax.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply