In this tutorial, we’ll learn what Python string swapcase() method is and how to properly use it. We’ll go through multiple Python code examples to understand how swapcase() method works in Python.
- Introduction: Python String swapcase() Method
- Syntax of swapcase() Method
- Example 1: swapcase() applied on a Python String
- Example 2: swapcase() Method Return Value
Introduction: Python String swapcase() Method
This method converts the case format of all alphabets in a string. If an alphabet is in lowercase format then it’ll be converted to uppercase and vice versa.
Syntax of swapcase() Method
- Python string swapcase() method does not take any arguments.
- This method returns a string having all its alphabets converted to their opposite case format.
Example 1: swapcase() applied on a Python String
strValue='This IS PythON.' print(strValue.swapcase()) print('PYTHON'.swapcase()) print('python'.swapcase()) print('PYThon'.swapcase()) print('pytHoN'.swapcase())
tHIS is pYTHon. python PYTHON pytHON PYThOn
We can see that all the alphabets in the above strings are converted to their opposite case format(converted to lowercase if alphabet is initially in uppercase and vice versa).
See below example as well in which Python string swapcase method is applied on a string having non-English alphabet.
print('groß'.swapcase()) // ß its a german word(ß is ss in English)
GROSS // ß is ss in English so its converted to capital SS
Example 2: swapcase() Method Return Value
val='This Is Python.' returnedVal=val.swapcase() print(returnedVal)
tHIS iS pYTHON.
We can see that Python string swapcase method returned a new string having all the alphabets converted to their opposite case format(uppercase if its initially in lowercase format and vice versa).
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string swapcase method. I’d be very delighted to have your feedback on this post. Thank you for reading it.