The swapcase() method returns the string by converting all the characters to their opposite letter case( uppercase to lowercase and vice versa).
Example
swapcase() Syntax
The syntax of the swapcase() method is:
string.swapcase()
swapcase() Parameters
The swapcase() method doesn't take any parameters.
swapcase() Return Value
The swapcase() method returns:
- the string after converting its uppercase characters to lowercase, and lowercase characters to uppercase.
Example 1: Python swapcase()
Output
this should all be lowercase. THIS SHOULD ALL BE UPPERCASE. tHiS sHoUlD bE mIxEd CaSeD.
In the above example, we have used the swapcase() method to convert lowercase characters to uppercase and vice versa.
Here,
sentence1.swapcase()- converts every uppercase character in"THIS SHOULD ALL BE LOWERCASE."to lowercasesentence2.swapcase()- converts every lowercase character in"this should all be uppercase."to uppercasesentence3.swapcase()- converts the mixed stringsentence3i.e."ThIs ShOuLd Be MiXeD cAsEd."to opposite letter case
Example 2: swapcase() with Non-English character
Not necessarily, string.swapcase().swapcase() == string. For example,
Output
GROSS gross False
In the above example, we have used the swapcase() method with the German word 'groß'. The letter 'ß' is 'ss' in English.
Here,
text.swapcase()- converts'groß'to uppercase i.e.'GROSS'text.swapcase().swapcase()- converts'GROSS'to lowercase i.e.'gross'
Hence the new string 'gross' is not equal to text.
Note: If you want to convert a string to lowercase only, use lower(). Likewise, if you want to convert string to uppercase only, use upper().