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.
+ There are no comments
Add yours