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
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
string.swapcase()
- 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())
Output
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)
Output
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)
Output
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).
Conclusion
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.