The swapcase() method returns the string where all the upper case letters are lower case and vice versa.
Python String swapcase()
The swapcase() is a built-in string handling Python method used to change the case of the string. The swapcase() method returns the string where all the uppercase letters are changed to lowercase letters and vice versa.
Syntax
See the following syntax.
string.swapcase()
Here, the string variable holds the input string on which the swapcase() method is applied.
Parameters
The swapcase() method doesn’t take any parameters. If any parameter is passed, it throws an error.
Return Value
The swapcase() function returns the string with the cases of the letters present in the string changed. Lowercase letters are changed to uppercase letters and vice versa.
Example
See the following code example.
# app.py h1= “Hello boY” h1.swapcase()
Output
hELLO BOy
Example programs on swapcase() method in python
Write the following program to show the mechanism of the swapcase() method.
# app.py h1 = "MilEy CirUS" h2 = "Hello Boy" h3 = "Qwerty" h4 = "HELLO girl" h5 = "lionel messi IS THE BEST" print("Original String: ", h1, "Case changed: ", h1.swapcase()) print("Original String: ", h2, "Case changed: ", h2.swapcase()) print("Original String: ", h3, "Case changed: ", h3.swapcase()) print("Original String: ", h4, "Case changed: ", h4.swapcase()) print("Original String: ", h5, "Case changed: ", h5.swapcase())
Output
Original String: MilEy CirUS Case changed: mILeY cIRus Original String: Hello Boy Case changed: hELLO bOY Original String: Qwerty Case changed: qWERTY Original String: HELLO girl Case changed: hello GIRL Original String: lionel messi IS THE BEST Case changed: LIONEL MESSI is the best
Example 2: Take two strings as input and print “They are same” if after using swapcase() method on one of the strings, it returns the same value; otherwise, print “They are not same”.
See the following program.
# app.py h1 = "MIKE" h2 = "mike" if(h1.swapcase() == h2): print("THEY ARE SAME") else: print("THEY ARE NOT SAME")
Output
THEY ARE SAME
That’s it for this tutorial.