AppDividend
Latest Code Tutorials

Python String swapcase() Method Example

0

Python string swapcase() is an inbuilt string handling method that is 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. The swapcase() method returns the string where all the upper case letters are lower case and vice versa.

Python String swapcase()

See the following syntax.

string.swapcase()

Here string is the string variable that holds the input string on which swapcase() method is applied.

The swapcase() method doesn’t take any parameters.

See the following code example.

# app.py

h1= “Hello boY”
h1.swapcase()

Output

hELLO BOy 

Parameters

No parameters are passed in the swapcase() method. If any parameter is passed, it throws an error.

Return Value

It 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 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

Finally, Python String swapcase() Method Example is over.

See also

Python string isupper islower upper lower functions

Python string title()

Python string format()

Python string capitalize()

Python string isalpha()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.